Note that there are some explanatory texts on larger screens.

plurals
  1. POHowto: download a file keeping the original name in C#?
    primarykey
    data
    text
    <p>I have files on a server that can be accessed from a URL formatted like this: http:// address/Attachments.aspx?id=GUID</p> <p>I have access to the GUID and need to be able to download multiple files to the same folder.</p> <p>if you take that URL and throw it in a browser, you will download the file and it will have the original file name.</p> <p>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.</p> <p>Is it possible to download a file preserving the original file name?</p> <p><strong>Update:</strong></p> <p>Using the fantastic answer below to use the WebReqest class I came up with the following which works perfectly:</p> <pre><code> 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)); } </code></pre> <p>Just had to do a little string manipulation to get the actual filename. I'm so excited. Thanks everyone!</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload