简体   繁体   中英

Howto: download a file keeping the original name in C#?

I have files on a server that can be accessed from a URL formatted like this: http:// address/Attachments.aspx?id=GUID

I have access to the GUID and need to be able to download multiple files to the same folder.

if you take that URL and throw it in a browser, you will download the file and it will have the original file name.

I want to replicate that behavior in C#. I have tried using the WebClient class's DownloadFile method, but with that you have to specify a new file name. And even worse, DownloadFile will overwrite an existing file. I know I could generate a unique name for every file, but i'd really like the original.

Is it possible to download a file preserving the original file name?

Update:

Using the fantastic answer below to use the WebReqest class I came up with the following which works perfectly:

    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));            
    }

Just had to do a little string manipulation to get the actual filename. I'm so excited. Thanks everyone!

As hinted in comments, the filename will be available in Content-Disposition header. Not sure about how to get its value when using WebClient , but it's fairly simple with 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();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM