Get original filename when downloading with WebClient

允我心安 提交于 2019-12-04 22:32:29

You need to examine the response headers and see if there is a content-disposition header present which includes the actual filename.

WebClient wc = new WebClient();
var data=   wc.DownloadData(@"www.sometime.com\getfile?id=123");
string fileName = "";

// Try to extract the filename from the Content-Disposition header
if (!String.IsNullOrEmpty(wc.ResponseHeaders["Content-Disposition"]))
{
 fileName = wc.ResponseHeaders["Content-Disposition"].Substring(wc.ResponseHeaders["Content-Disposition"].IndexOf("filename=") + 9).Replace("\"", "");
}

Read the Response Header "Content-Disposition" with WebClient.ResponseHeaders

It should be:

    Content-Disposition: attachment; filename="fname.ext"

your code should look like:

string header = wc.ResponseHeaders["Content-Disposition"]??string.Empty;
const string filename="filename=";
int index = header.LastIndexOf(filename,StringComparison.OrdinalIgnoreCase);
if (index > -1)
{
    fileName = header.Substring(index+filename.Length);
}

To get the filename without downloading the file:

public string GetFilenameFromWebServer(string url)
{
    string result = "";

    var req = System.Net.WebRequest.Create(url);
    req.Method = "HEAD";
    using (System.Net.WebResponse resp = req.GetResponse())
    {
        // Try to extract the filename from the Content-Disposition header
        if (!string.IsNullOrEmpty(resp.Headers["Content-Disposition"]))
        {
            result = resp.Headers["Content-Disposition"].Substring(resp.Headers["Content-Disposition"].IndexOf("filename=") + 9).Replace("\"", "");
        }
    }

    return result;
}

If you, like me, have to deal with a Content-Disposition header that is not formatted correctly or cannot be parsed automatically by the ContentDisposition class for some reason, here's my solution :

string fileName = null;

// Getting file name
var request = WebRequest.Create(url);
request.Method = "HEAD";

using (var response = request.GetResponse())
{
    // Headers are not correct... So we need to parse manually
    var contentDisposition = response.Headers["Content-Disposition"];

    // We delete everything up to and including 'Filename="'
    var fileNameMarker= "filename=\"";
    var beginIndex = contentDisposition.ToLower().IndexOf(fileNameMarker);
    contentDisposition = contentDisposition.Substring(beginIndex + fileNameMarker.Length);

    //We only get the string until the next double quote
    var fileNameLength = contentDisposition.ToLower().IndexOf("\"");
    fileName = contentDisposition.Substring(0, fileNameLength);
}
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!