我想从远程URL获取实际的文件扩展名。

有时扩展名格式无效。

例如,我从下面的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


我想从远程URL下载/保存远程图像。

如何从上述网址获取文件名和扩展名?

谢谢
阿比舍克

最佳答案

远程服务器发送一个Content-Type标头,其中包含资源的mime类型。例如:

Content-Type: image/png


因此,您可以检查此标头的值并为文件选择适当的扩展名。例如:

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);
    }
}

关于c# - 如何从远程URL获取有效的文件名和扩展名以进行保存?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/7280885/

10-10 21:45
查看更多