28

We are providing files that are saved in our database and the only way to retrieve them is by going by their id as in:

www.AwesomeURL.com/AwesomeSite.aspx?requestedFileId=23

Everything is working file as I am using the WebClient Class.

There's only one issue that I am facing:

How can I get the real filename?

My code looks like this atm:

WebClient client = new WebClient ();

string url = "www.AwesomeURL.com/AwesomeSite.aspx?requestedFileId=23";

client.DownloadFile(url, "IDontKnowHowToGetTheRealFileNameHere.txt");

All I know is the id.

This does not happen when I try accessing url from the browser where it get's the proper name => DownloadedFile.xls.

What's the proper way to get the correct response?

4
  • Have you found the solution? If none of the answers here helped you and you found it, please share it with us. :) Nov 8, 2011 at 11:37
  • I actually didn't find any solution yet.. stashed the code and still waiting for some random inspiration ;)
    – Faizan S.
    Nov 8, 2011 at 20:56
  • So what happens when you try the code suggested in my answer? You never commented in there.. Nov 9, 2011 at 7:51
  • How could I get the encoding of filename? If I use HttpWebResponse I can use StreamReader sr = new StreamReader(s, Encoding.GetEncoding(response.CharacterSet));
    – Nime Cloud
    Mar 21, 2012 at 10:25

8 Answers 8

26

I had the same problem, and I found this class: System.Net.Mime.ContentDisposition.

using (WebClient client = new WebClient()){
    client.OpenRead(url);

    string header_contentDisposition = client.ResponseHeaders["content-disposition"];
    string filename = new ContentDisposition(header_contentDisposition).FileName;

    ...do stuff...
}

The class documentation suggests it's intended for email attachments, but it works fine on the server I used to test, and it's really nice to avoid the parsing.

2
  • How can I get the encoding of filename? If I use HttpWebResponse I can use StreamReader sr = new StreamReader(s, Encoding.GetEncoding(response.CharacterSet));
    – Nime Cloud
    Mar 21, 2012 at 9:48
  • @NimeCloud I'm pretty sure WebClient tries to read the header and set the encoding automatically. If it's not in the header or is corrupt, you should be able to set it ahead of time with WebClient.Encoding.
    – wst
    Apr 11, 2012 at 20:19
24

Here is the full code required, assuming the server has applied content-disposition header:

using (WebClient client = new WebClient())
{
    using (Stream rawStream = client.OpenRead(url))
    {
        string fileName = string.Empty;
        string contentDisposition = client.ResponseHeaders["content-disposition"];
        if (!string.IsNullOrEmpty(contentDisposition))
        {
            string lookFor = "filename=";
            int index = contentDisposition.IndexOf(lookFor, StringComparison.CurrentCultureIgnoreCase);
            if (index >= 0)
                fileName = contentDisposition.Substring(index + lookFor.Length);
        }
        if (fileName.Length > 0)
        {
            using (StreamReader reader = new StreamReader(rawStream))
            {
                File.WriteAllText(Server.MapPath(fileName), reader.ReadToEnd());
                reader.Close();
            }
        }
        rawStream.Close();
    }
}

If the server did not set up this header, try debugging and see what ResponseHeaders you do have, one of them will probably contain the name you desire. If the browser show the name, it must come from somewhere.. :)

10
  • 1
    If I'm not mistaken, you forgot to remove the surrounding quotes from the file name. i.e. "file.txt" instead of file.txt. Nov 8, 2011 at 11:29
  • As far as I know it shouldn't be wrapped with quotes, but removing them is as easy as fileName = contentDisposition.Substring(index + lookFor.Length).Replace("\"", ""); :) Nov 8, 2011 at 11:36
  • 1
    Maybe it was just the server I used. Another note - this works only for text files, at most cases I guess it's better to write bytes rather than text. You can just replace the StreamReader with a MemoryStream, and then use rawStream.CopyTo(memStream) and File.WriteAllBytes(path, memStream.ToArray()) (.NET 4 only). Nov 8, 2011 at 13:15
  • I am new to this part of C#. So, I want to know if there is a way to get the file name without knowing the header which contains the filename? I may be using random sites!
    – Writwick
    Aug 21, 2012 at 17:07
  • 1
    @Shadow Thanks, I will try the Chrome Developer tools! In .NET 4 [Dont know about others], one can Use the System.Net.Mime.ContentDisposition by instancing from the string returned by client.ResponseHeaders["content-disposition"][I had been using WebResponse so i used Response.Headers["Content-Disposition"] the name of the file is contained in the FileName property and we can also check if the Content-Disposition is Inline or not, which will determine that should we use the Url or the Content-Disposition to get the Filename.
    – Writwick
    Aug 22, 2012 at 12:15
10

You need to look at the content-disposition header, via:

string disposition = client.ResponseHeaders["content-disposition"];

a typical example would be:

"attachment; filename=IDontKnowHowToGetTheRealFileNameHere.txt"
6
  • I don't think he is worrying about the server-side. Nov 4, 2010 at 13:12
  • @Daniel - who said anything about the server? The client is responsible for reading this header... Nov 4, 2010 at 13:13
  • Thanks for adding that - I didn't see that the WebClient had access to the response headers. Nov 4, 2010 at 13:14
  • Interesting, I am getting the content-disposition after the download and the code throws a NullReferenceException | Is there any other place this could be placed?
    – Faizan S.
    Nov 4, 2010 at 13:20
  • @Shaharyar - run it through Fiddler. If it doesn't send that header, then frankly you are just going to have to make up a name. Nov 4, 2010 at 13:23
4

I achieve this with the code of wst.

Here is the full code to download the url file in c:\temp folder

public static void DownloadFile(string url)
    {
        using (WebClient client = new WebClient())
        {
            client.OpenRead(url);

            string header_contentDisposition = client.ResponseHeaders["content-disposition"];
            string filename = new ContentDisposition(header_contentDisposition).FileName;


            //Start the download and copy the file to the destinationFolder
            client.DownloadFile(new Uri(url), @"c:\temp\" + filename);
        }

    }
3

You can use HTTP content-disposition header to suggest filenames for the content you are providing:

Content-Disposition: attachment; filename=downloadedfile.xls;

So, in your AwesomeSite.aspx script, you would set the content-disposition header. In your WebClient class you would retrieve that header to save the file as suggested by your AwesomeSite site.

0
1

Although the solution proposed by Shadow Wizard works well for text files, I needed to support downloading binary files, such as pictures and executables, in my application.

Here is a small extension to WebClient that does the trick. Download is asynchronous. Also default value for file name is required, because we don't really know if the server would send all the right headers.

static class WebClientExtensions
{
    public static async Task<string> DownloadFileToDirectory(this WebClient client, string address, string directory, string defaultFileName)
    {
        if (!Directory.Exists(directory))
            throw new DirectoryNotFoundException("Downloads directory must exist");

        string filePath = null;

        using (var stream = await client.OpenReadTaskAsync(address))
        {
            var fileName = TryGetFileNameFromHeaders(client);
            if (string.IsNullOrWhiteSpace(fileName))
                fileName = defaultFileName;

            filePath = Path.Combine(directory, fileName);
            await WriteStreamToFile(stream, filePath);
        }

        return filePath;
    }

    private static string TryGetFileNameFromHeaders(WebClient client)
    {
        // content-disposition might contain the suggested file name, typically same as origiinal name on the server
        // Originally content-disposition is for email attachments, but web servers also use it.
        string contentDisposition = client.ResponseHeaders["content-disposition"];
        return string.IsNullOrWhiteSpace(contentDisposition) ?
            null :
            new ContentDisposition(contentDisposition).FileName;
    }

    private static async Task WriteStreamToFile(Stream stream, string filePath)
    {
        // Code below will throw generously, e. g. when we don't have write access, or run out of disk space
        using (var outStream = new FileStream(filePath, FileMode.CreateNew))
        {
            var buffer = new byte[8192];
            while (true)
            {
                int bytesRead = await stream.ReadAsync(buffer, 0, buffer.Length);
                if (bytesRead == 0)
                    break;
                // Could use async variant here as well. Probably helpful when downloading to a slow network share or tape. Not my use case.
                outStream.Write(buffer, 0, bytesRead);
            }
        }
    }
}
0

Ok, my turn.

I had a few things in mind when I tried to "download the file":

  1. Use only HttpClient. I had a couple of extension methods over it, and it wasn't desirable to create other extensions for WebClient.
  2. It was mandatory for me also to get a File name.
  3. I had to write the result to MemoryStream but not FileStream.

Solution

So, for me, it turned out to be this code:

// assuming that httpClient created already (including the Authentication cumbersome)
var response = await httpClient.GetAsync(absoluteURL);  // call the external API

// reading file name from HTTP headers
var fileName = response.Content.Headers.ContentDisposition.FileNameStar; // also available to read from ".FileName"

// reading file as a byte array
var fileBiteArr = await response.Content
                        .ReadAsByteArrayAsync()
                        .ConfigureAwait(false); 

var memoryStream = new MemoryStream(fileBiteArr); // memory streamed file
            

Test

To test that the Stream contains what we have, we can check it by converting it to file:

// getting the "Downloads" folder location, can be anything else
string pathUser = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile);
string downloadPath = Path.Combine(pathUser, "Downloads\\"); 

using (FileStream file =
                 new FileStream(
                     $"{downloadPath}/file.pdf", 
                     FileMode.Create, 
                     FileAccess.Write))
{
     byte[] bytes = new byte[memoryStream .Length];
     memoryStream.Read(bytes, 0, (int)memoryStream.Length);

     file.Write(bytes, 0, bytes.Length);
     memoryStream.Close();
}

0

This is my working code:

using (var client = new HttpClient())
   using (var result = await client.GetAsync(downloadUrl))
       if (result.IsSuccessStatusCode)
       {
        string fileName = string.Empty;
        if (result.Content.Headers.ContentDisposition != null)
        {
          fileName = System.Net.WebUtility.UrlDecode(result.Content.Headers.ContentDisposition.FileName).Replace("\"", "");
        }
        ...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.