I want to get actual file extension from the remote url.
sometimes extension not in valid format.
for example
I getting problem from below UR开发者_StackOverflow中文版Ls1) 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
I want to download/save remote image from remote url..
How to get filename and extension from the above url?
Thanks
AbhishekThe remote server sends a Content-Type
header containing the mime type of the resource. For example:
Content-Type: image/png
So you can examine the value of this header and pick the proper extension for your file. For example:
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);
}
}
You can use the VirtualPathUtility if you want to extract the extension from a URL.
var ext = VirtualPathUtility.GetExtension(pathstring)
Or use headers to determine the content type. There's a Windows API to convert content type to extension (it's also in registry), but for web apps it makes sense to use mapping.
switch(response.ContentType)
{
case "image/jpeg":
return ".jpeg";
case "image/png":
return ".png";
}
精彩评论