gpt4 book ai didi

c# - 如何使用 C# 识别文件的扩展名/类型?

转载 作者:太空狗 更新时间:2023-10-29 20:52:17 24 4
gpt4 key购买 nike

我有一个工作流程,允许用户上传任何文件,然后该文件将被读取。

现在我的问题是,如果用户有图像文件 xyz.jpg 并且他仅将其重命名为 xyz(删除扩展名),那么我们仍然可以使用/读取文件数据/元数据来获取文件的类型/扩展名。

谢谢大家

最佳答案

参见 PInvoke.net更多详情

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

示例用法:

  public string MimeTypeFrom(byte[] dataBytes, string mimeProposed) {
if (dataBytes == null)
throw new ArgumentNullException("dataBytes");
string mimeRet = String.Empty;
IntPtr suggestPtr = IntPtr.Zero, filePtr = IntPtr.Zero, outPtr = IntPtr.Zero;
if (mimeProposed != null && mimeProposed.Length > 0) {
//suggestPtr = Marshal.StringToCoTaskMemUni(mimeProposed); // for your experiments ;-)
mimeRet = mimeProposed;
}
int ret = FindMimeFromData(IntPtr.Zero, null, dataBytes, dataBytes.Length, mimeProposed, 0, out outPtr, 0);
if (ret == 0 && outPtr != IntPtr.Zero) {
//todo: this leaks memory outPtr must be freed
return Marshal.PtrToStringUni(outPtr);
}
return mimeRet;
}

// call it this way:
Trace.Write("MimeType is " + MimeTypeFrom(Encoding.ASCII.GetBytes("%PDF-"), "text/plain"));

另一个例子:

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

关于c# - 如何使用 C# 识别文件的扩展名/类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2826808/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com