Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 486
nitewulf50 Avatar asked Oct 12 '25 21:10

nitewulf50


1 Answers

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();
like image 73
Nikola Anusev Avatar answered Oct 14 '25 11:10

Nikola Anusev