【问题标题】:C# downloading image without extensionC#下载没有扩展名的图像
【发布时间】:2013-06-28 18:01:45
【问题描述】:

我正在从一些网站下载许多图像。我可以收集所有 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),但它不适用于这样的链接。

【问题讨论】:

  • 如果扩展程序不是由网络服务器提供的,您将无法获取它。不过,您可以尝试从内容类型中推断出来。

标签: c# image download webclient


【解决方案1】:

我认为这个问题的答案会如你所愿: how to identify the extension/type of the file using 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;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-03-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多