我们提供保存在我们数据库中的文件,检索它们的唯一方法是id按照以下方式进行操作:
www.AwesomeURL.com/AwesomeSite.aspx?requestedFileId=23
当我使用WebClient类时,一切都正常工作.
我面临的问题只有一个:
我怎样才能获得真实的文件名?
我的代码看起来像这个atm:
WebClient client = new WebClient ();
string url = "www.AwesomeURL.com/AwesomeSite.aspx?requestedFileId=23";
client.DownloadFile(url, "IDontKnowHowToGetTheRealFileNameHere.txt");
Run Code Online (Sandbox Code Playgroud)
我所知道的就是身份证.
当我尝试url从浏览器访问时,这不会发生,因为它得到了正确的名称=> DownloadedFile.xls.
获得正确答案的正确方法是什么?
wst*_*wst 25
我遇到了同样的问题,我找到了这个类: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...
}
Run Code Online (Sandbox Code Playgroud)
类文档建议它用于电子邮件附件,但它在我以前测试的服务器上工作正常,并且避免解析非常好.
Sha*_*ard 23
假设服务器已应用content-disposition标头,以下是所需的完整代码:
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();
}
}
Run Code Online (Sandbox Code Playgroud)
如果服务器没有设置此标头,请尝试调试并查看您拥有的ResponseHeaders,其中一个可能包含您想要的名称.如果浏览器显示名称,它必须来自某个地方 .. :)
您需要通过以下方式查看content-disposition标题:
string disposition = client.ResponseHeaders["content-disposition"];
Run Code Online (Sandbox Code Playgroud)
一个典型的例子是:
"attachment; filename=IDontKnowHowToGetTheRealFileNameHere.txt"
Run Code Online (Sandbox Code Playgroud)
您可以使用 HTTPcontent-disposition标头为您提供的内容建议文件名:
Content-Disposition: attachment; filename=downloadedfile.xls;
Run Code Online (Sandbox Code Playgroud)
因此,在您的AwesomeSite.aspx脚本中,您将设置content-disposition标题。在您的WebClient课程中,您将检索该标头以按照站点的建议保存文件AwesomeSite。