我想从远程网址获得实际的文件扩展名.
有时扩展名不是有效格式.
例如,
我从下面的URL中遇到问题
1) http://tctechcrunch2011.files.wordpress.com/2011/09/media-upload.png?w=266
2) http://0.gravatar.com/avatar/a5a5ed70fa7c651aa5ec9ca8de57a4b8?s=60&d=identicon&r=G
Run Code Online (Sandbox Code Playgroud)
我想从远程网址下载/保存远程图像..
如何从上面的URL获取文件名和扩展名?
谢谢
Abhishek
远程服务器发送Content-Type包含资源的mime类型的标头.例如:
Content-Type: image/png
Run Code Online (Sandbox Code Playgroud)
因此,您可以检查此标头的值,并为您的文件选择适当的扩展名.例如:
WebRequest request = WebRequest.Create("http://0.gravatar.com/avatar/a5a5ed70fa7c651aa5ec9ca8de57a4b8?s=60&d=identicon&r=G");
using (WebResponse response = request.GetResponse())
using (Stream stream = response.GetResponseStream())
{
string contentType = response.ContentType;
// TODO: examine the content type and decide how to name your file
string filename = "test.jpg";
// Download the file
using (Stream file = File.OpenWrite(filename))
{
// Remark: if the file is very big read it in chunks
// to avoid loading it into memory
byte[] buffer = new byte[response.ContentLength];
stream.Read(buffer, 0, buffer.Length);
file.Write(buffer, 0, buffer.Length);
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6043 次 |
| 最近记录: |