我似乎找不到我的问题的有效答案,我想知道是否有人可以提供帮助。基本上我的网站上有一个链接,可以下载一个 zip 文件:
http://***.com/download.php?id=1
如果您在网页上激活此链接,它将弹出另存为对话框,并让您使用默认名称保存文件ThisIsMyZipFile.zip
我的问题是,在 c# 下,如果我使用new Uri("http://***.com/download.pgp?id=1").IsFile
它会返回false
,所以如果不执行 awebclient DownloadString
并查看前两个字节是否为PK
.
此外,即使手动下载为字符串检测PK
标题并保存文件,我也无法找出我的网站想要使用的默认文件名,ThisIsMyZipFile.zip
因为我想使用相同的文件名。
请问有人知道解决这两个问题的好方法吗?
更新
感谢 Paul 和他的回答,我创建了以下函数,它完全符合我的需要:
/// <summary>
/// Returns the responded HTTP headers of the given URL and if the link refers to the file it returns extra information about it.
/// </summary>
/// <param name="Url">The address.</param>
/// <returns>
/// null if a WebException is thrown
/// otherwise:
/// List of headers:
/// Keep-Alive - Timeout value (i.e. timeout=2, max=100)
/// Connection - The type of connection (i.e. Keep-Alive)
/// Transfer-Encoding - The type of encoding used for the transfer (i.e. chunked)
/// Content-Type - The type of Content that will be transferred (i.e. application/zip)
/// Date - The servers date and time
/// Server - The server that is handling the request (i.e. Apache)
/// AbsoluteUri - The full Uri of the resulting link that will be followed.
/// The following key will be present if the link refers to a file
/// Filename - The filename (not path) of the file that will be downloaded if the link if followed.
/// </returns>
public Dictionary<string, string> GetHTTPResponseHeaders(string Url)
{
WebRequest WebRequestObject = HttpWebRequest.Create(Url);
WebResponse ResponseObject = null;
try
{
ResponseObject = WebRequestObject.GetResponse();
}
catch(WebException ex)
{
return null;
}
// Add the header inforamtion to the resulting list
Dictionary<string, string> HeaderList = new Dictionary<string, string>();
foreach (string HeaderKey in ResponseObject.Headers)
HeaderList.Add(HeaderKey, ResponseObject.Headers[HeaderKey]);
// Add the resolved Uri to the resulting list
HeaderList.Add("AbsoluteUri", ResponseObject.ResponseUri.AbsoluteUri);
// If this is a zip file then add the download filename specified by the server to the resulting list
if (ResponseObject.ContentType.ToLower() == "application/zip")
{
HeaderList.Add("Filename", ResponseObject.ResponseUri.Segments[ResponseObject.ResponseUri.Segments.Length-1]);
}
// We are now finished with our response object
ResponseObject.Close();
// Return the resulting list
return HeaderList;
}