Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/265.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/.net/20.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 使用WebClient下载时获取原始文件名_C#_.net_Webclient - Fatal编程技术网

C# 使用WebClient下载时获取原始文件名

C# 使用WebClient下载时获取原始文件名,c#,.net,webclient,C#,.net,Webclient,当Uri不包含文件名时,有没有办法知道您使用WebClient下载的文件的原始名称 例如,在下载源于动态页面的站点中,这种情况会发生,而该页面的名称事先不知道 使用我的浏览器,该文件将获得正确的名称。但是如何使用WebClient实现这一点呢? 例如 使用DownloadFile()不是一个解决方案,因为此方法需要提前输入文件名。使用 应该是: Content-Disposition: attachment; filename="fname.ext" 您的代码应该如下所示: strin

当Uri不包含文件名时,有没有办法知道您使用WebClient下载的文件的原始名称

例如,在下载源于动态页面的站点中,这种情况会发生,而该页面的名称事先不知道

使用我的浏览器,该文件将获得正确的名称。但是如何使用WebClient实现这一点呢? 例如


使用DownloadFile()不是一个解决方案,因为此方法需要提前输入文件名。

使用

应该是:

    Content-Disposition: attachment; filename="fname.ext"
您的代码应该如下所示:

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

您需要检查响应头并查看是否存在包含实际文件名的内容处置头

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("\"", "");
}

如果您和我一样,必须处理格式不正确或由于某种原因无法由ContentDisposition类自动解析的内容处置标头,我的解决方案如下:

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

要在不下载文件的情况下获取文件名,请执行以下操作:

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

您是否尝试过检查厕所负责人?文件下载通常包含一个文件名为.Tobberoth的附件头。这确实是答案!我不知道。非常感谢!一些从动态页面下载的站点会生成重定向,并且不会在重定向的响应上设置“内容处置”,因此您可以使用HttpClient with AutoRedirect=false,使用HEAD方法,然后从响应中获取“location”头。回答很好,但索引需要提前以说明“filename=”的长度。IMHO我会将其更改为fileName=header.Substring(index+“fileName=”.Length);
System.Net.Mime.ContentDisposition
可用于解析标题
var header=newcontentDisposition(wc.ResponseHeaders[“Content Disposition”])
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;
}