Abhishek B.
Abhishek B.

Reputation: 5202

How to get valid file name and extension from remote url to save it.?

I want to get actual file extension from the remote url.

sometimes extension not in valid format.

for example
I getting problem from below URLs

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

I want to download/save remote image from remote url..

How to get filename and extension from the above url?

Thanks
Abhishek

Upvotes: 1

Views: 7327

Answers (2)

TheCodeKing
TheCodeKing

Reputation: 19220

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

Upvotes: 0

Darin Dimitrov
Darin Dimitrov

Reputation: 1038890

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

Upvotes: 6

Related Questions