0

我正在从一些网站下载许多图像。我可以收集所有 img 源,但有时我会得到这样的源:something.com/folder/123 - 其中 123 是 gif 文件,但链接没有“gif”扩展名。当我像这样保存这个文件时

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

它保存此 gif 文件而没有扩展名。当链接不提供时,如何获取此文件的扩展名?我尝试了 System.IO.Path.GetFileName(link),但它不适用于这样的链接。

4

1 回答 1

0

我认为这个问题的答案会如你所愿: 如何使用 C# 识别文件的扩展名/类型?

这将允许您检测以下 mime 类型:http: //msdn.microsoft.com/en-us/library/ms775147%28VS.85%29.aspx#Known_MimeTypes

从中复制/粘贴:

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

示例用法:

/// <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;
}
于 2013-07-01T15:54:04.820 回答