0

这是一个代码,C#。

System.Net.HttpWebRequest _Response =
    (HttpWebRequest)System.Net.WebRequest.Create(e.Uri.AbsoluteUri.ToString());
_Response.Method = "GET";
_Response.Timeout = 120000;
_Response.Accept =
    "application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5";
_Response.Headers.Add("Accept-Encoding", "gzip,deflate,sdch");
_Response.Headers.Add("Accept-Language", "ru-RU,ru;q=0.8,en-US;q=0.6,en;q=0.4");
_Response.Headers.Add("Accept-Charset", "windows-1251,utf-8;q=0.7,*;q=0.3");
_Response.AllowAutoRedirect = false;

System.Net.HttpWebResponse result = (HttpWebResponse)_Response.GetResponse();

for (int i = 0; i < result.Headers.Count; i++)
{
    MessageBox.Show(result.Headers.ToString());
}

这是一个结果,

Cache-Control: private
Content-Type: text/html
Date: Tue, 06 Sep 2011 17:38:26 GMT
ETag: 
Location: http://fs31.filehippo.com/6428/59e79d1f80a74ead98bb04517e26b730/Firefox Setup 7.0b3.exe
Server: Microsoft-IIS/6.0
X-Powered-By: ASP.NET
4

7 回答 7

3

正确的方法是查看Content-Disposition字段是否提供了文件名,如果失败,则尝试从 Location 字段中推断文件名。

请注意,位置字段只是下载请求的 URL,因此可能不包含扩展名甚至是有意义的名称。

于 2011-09-06T18:53:24.030 回答
2

像这样做:

    string fileName = Path.GetFileName(result.Headers["Location"]);

这样,您将在位置标题的末尾有文件名。

于 2011-09-06T17:47:50.987 回答
1

鉴于您请求的标头,您应该能够:

 string file = result.Headers["Location"];
于 2011-09-06T17:44:22.517 回答
1

如果你有文件的位置,你可以只提取你想要的标题(在这种情况下,我想它被索引在4或 at "Location"),然后获取 URL 的最后一部分。

于 2011-09-06T17:45:43.310 回答
0

由于文件位于服务器上,您将无法检索实际文件名。只有 Web 应用程序告诉您的内容。

此文件名在“位置”中。

但是,由于应用程序告诉您它是 text/html,因此它可能会在将结果发送给您之前对其进行格式化。可执行文件的正确 mime 类型是 application/octet-stream。

另一个注意事项。看来您正在下载文件,在这种情况下无需提供路径。您下载的文件的路径将是您将下载流的内容放入的任何路径。因此,您保存文件并将其放在您有权放置的任何地方。

创建文件时,您必须提供路径,否则它将与调用它的可执行文件放在同一目录中。

我希望这有帮助

于 2011-09-06T18:02:08.213 回答
0

如果一切都失败了,您总是可以解析 WebResponse.ResponseUri.ToString()。使用 string.LastIndexOf("/") 查找文件名的开头,使用 String.IndexOf 查看是否有“?”。

public static void ExtractFileNameFromUri(string URI, ref string parsedFileName, string fileNameStartDelimiter = "/", string fileNameEndDelimiter = "?")
{
    const int NOTFOUND = -1;

    try
    {
        int startParse = URI.LastIndexOf(fileNameStartDelimiter) + fileNameStartDelimiter.Length;

        if (startParse == NOTFOUND)
            return;

        int endParse = URI.IndexOf(fileNameEndDelimiter);

        if (endParse == NOTFOUND)
            endParse = URI.Length;

        parsedFileName = URI.Substring(startParse, (endParse - startParse));
    }
    catch (Exception e)
    {
        Console.WriteLine(e);
        return;
    }
}
于 2018-12-04T21:49:43.780 回答
0

从 Content-Disposition 字段中检索文件名的简单有效的方法:

using System.Net.Mime;

HttpWebResponse resp = {YOUR RESPONSE}
string dispHeader = resp.GetResponseHeader("content-disposition");
ContentDisposition disp = new ContentDisposition(dispHeader);
string filename = disp.FileName;
于 2020-08-23T21:56:30.413 回答