0

I'm downloading many images from some web sites. I can collect all img sources, but sometimes i get source like this: something.com/folder/123 - where 123 is a gif file, but link doesn't have 'gif' extension. When i save this file like this

link = getLink(); //link = something.com/folder/123 in this example
myWebClient.DownloadFile(link, link)

It saves this gif file without extension. How can i get extension for this file, when link doesn't provide it? I tried System.IO.Path.GetFileName(link), but it doesn't work good for links like this.

Piotr Łużecki
  • 1,031
  • 4
  • 17
  • 33

1 Answers1

0

I think the answer to this question will do what you want: how to identify the extension/type of the file using C#?

This will allow you to detect the following mime types: http://msdn.microsoft.com/en-us/library/ms775147%28VS.85%29.aspx#Known_MimeTypes

Copy/paste from it:

  [DllImport("urlmon.dll", CharSet = CharSet.Unicode, ExactSpelling = true, SetLastError = false)]
    static extern int FindMimeFromData(IntPtr pBC,
          [MarshalAs(UnmanagedType.LPWStr)] string pwzUrl,
         [MarshalAs(UnmanagedType.LPArray, ArraySubType=UnmanagedType.I1, SizeParamIndex=3)] 
        byte[] pBuffer,
          int cbSize,
             [MarshalAs(UnmanagedType.LPWStr)]  string pwzMimeProposed,
          int dwMimeFlags,
          out IntPtr ppwzMimeOut,
          int dwReserved);

Sample usage:

/// <summary>
/// Ensures that file exists and retrieves the content type 
/// </summary>
/// <param name="file"></param>
/// <returns>Returns for instance "images/jpeg" </returns>
public static string getMimeFromFile(string file)
{
    IntPtr mimeout;
    if (!System.IO.File.Exists(file))
    throw new FileNotFoundException(file + " not found");

    int MaxContent = (int)new FileInfo(file).Length;
    if (MaxContent > 4096) MaxContent = 4096;
    FileStream fs = File.OpenRead(file);


    byte[] buf = new byte[MaxContent];        
    fs.Read(buf, 0, MaxContent);
    fs.Close();
    int result = FindMimeFromData(IntPtr.Zero, file, buf, MaxContent, null, 0, out mimeout, 0);

    if (result != 0)
    throw Marshal.GetExceptionForHR(result);
    string mime = Marshal.PtrToStringUni(mimeout);
    Marshal.FreeCoTaskMem(mimeout);
    return mime;
}
Community
  • 1
  • 1
Kendall Trego
  • 1,975
  • 13
  • 21