如何从 Response.Header 获取文件名? C#

发布于 2024-12-03 00:07:22 字数 1052 浏览 1 评论 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

This is a code, 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());
}

And this is a result,

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(7

默嘫て 2024-12-10 00:07:22

正确的方法是查看文件名是否由 Content-Disposition 字段,如果失败,则尝试从位置字段推断文件名。

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

The correct approach is to see if a filename is provided by the Content-Disposition field and, failing that, to attempt to infer a filename from the Location field.

Be aware than the location field is simply the URL for the download request, and as such may not include an extension or even a meaningful name.

晚风撩人 2024-12-10 00:07:22

这样做:

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

这样,您将在位置标头的末尾看到文件名。

Do it like this:

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

That way, you'll have the file name at the end of the location header.

森末i 2024-12-10 00:07:22

鉴于您的请求中的标头,您应该能够执行以下操作:

 string file = result.Headers["Location"];

Given your headers from your request, you should be able to do:

 string file = result.Headers["Location"];
与他有关 2024-12-10 00:07:22

如果您已经获得了文件的位置,则可以提取所需的标头(在本例中,我认为它的索引位置为 4"Location"),然后获取 URL 的最后一部分。

If you have got the location of the file you can just extract the header you want (in this case I suppose it is indexed at 4 or at "Location") and then take the last part of the URL.

生生不灭 2024-12-10 00:07:22

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

The easy and efficient way to retrieve filename from Content-Disposition field:

using System.Net.Mime;

HttpWebResponse resp = {YOUR RESPONSE}
string dispHeader = resp.GetResponseHeader("content-disposition");
ContentDisposition disp = new ContentDisposition(dispHeader);
string filename = disp.FileName;
删除→记忆 2024-12-10 00:07:22

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

该文件名位于“位置”中。

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

另一方面。您似乎正在下载该文件,在这种情况下不需要提供路径。您下载的文件的路径将是您将下载的流的内容放入其中的路径。
因此,您保存该文件并将其放置在您有权访问的任何位置。

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

我希望这有帮助

As the file is on a server you will not be able to retrieve the actual filename. Only what the web application is telling you.

This filename is in "Location".

However since the application is telling you that it is text/html it may be formatting the result before it sends it to you. The correct mime type for an executable is application/octet-stream.

On another note. It appears you are downloading the file in which case there is no need to be provided a path. The path of the file you download, is going to be whatever path you place the contents of the downloaded stream into.
Therefore you save the file and put it wherever you have access to put it.

When the file is created you have to provide a path, otherwise it is placed in the same directory as the executable that is calling it.

I hope this helps

離人涙 2024-12-10 00:07:22

如果其他方法都失败,您始终可以解析 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;
    }
}

If all else fails, you can always parse the WebResponse.ResponseUri.ToString(). Use string.LastIndexOf("/") to find the beginning of the file name and String.IndexOf to see if there is a "?".

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;
    }
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文