我在服务器上有文件,可以通过格式如下的 URL 访问: http://地址/Attachments.aspx?id=GUID
我可以访问 GUID,并且需要能够将多个文件下载到同一个文件夹。
如果您获取该 URL 并将其放入浏览器,您将下载该文件,并且它将具有原始文件名。
我想在 C# 中复制该行为。我试过使用 WebClient 类的 DownloadFile 方法,但是你必须指定一个新的文件名。更糟糕的是,下载文件会覆盖现有文件。我知道我可以为每个文件生成一个唯一的名称,但我真的很喜欢原来的名称。
是否可以下载保留原始文件名的文件?
更新:
使用下面的奇妙答案来使用 WebReqest 类,我想出了以下完美的方法:
public override void OnAttachmentSaved(string filePath)
{
var webClient = new WebClient();
//get file name
var request = WebRequest.Create(filePath);
var response = request.GetResponse();
var contentDisposition = response.Headers["Content-Disposition"];
const string contentFileNamePortion = "filename=";
var fileNameStartIndex = contentDisposition.IndexOf(contentFileNamePortion, StringComparison.InvariantCulture) + contentFileNamePortion.Length;
var originalFileNameLength = contentDisposition.Length - fileNameStartIndex;
var originalFileName = contentDisposition.Substring(fileNameStartIndex, originalFileNameLength);
//download file
webClient.UseDefaultCredentials = true;
webClient.DownloadFile(filePath, String.Format(@"C:\inetpub\Attachments Test\{0}", originalFileName));
}
只需要做一些字符串操作就可以得到实际的文件名。我太激动了。谢谢大家!
最佳答案
正如评论中所暗示的,文件名将在 Content-Disposition
header 中可用。不确定在使用 WebClient
时如何获取它的值,但使用 WebRequest
时相当简单:
WebRequest request = WebRequest.Create("http://address/Attachments.aspx?id=GUID");
WebResponse response = request.GetResponse();
string originalFileName = response.Headers["Content-Disposition"];
Stream streamWithFileBody = response.GetResponseStream();
关于c# - 如何 : download a file keeping the original name in C#?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13201059/