You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

UniformTypeIdentifiers的UTType始终返回null,无法获取PDF正确MIME类型

问题原因及解决办法

问题出在扩展名带点(.pdf)上:UTType.GetType方法接收的文件名扩展名标签需要是不带前缀点的纯扩展名(比如pdf而非.pdf),但Path.GetExtension(path)返回的结果默认带点,导致无法匹配到对应的UTI类型,最终返回null。

修复代码

var fileNanager = new NSFileManager();
if (!fileNanager.FileExists(path))
{
    return null;
}

// 移除扩展名开头的点号前缀
var extension = Path.GetExtension(path).TrimStart('.');
var uti = UniformTypeIdentifiers.UTType.GetType(extension, UniformTypeIdentifiers.UTTagClass.FilenameExtension, null);
var x = uti?.PreferredMimeType;

if (x == null)
{
    return "application/octet-stream";
}
return x;

可选优化方案

如果需要更精准的类型识别(比如文件扩展名被篡改的场景),可以直接基于文件实际内容获取UTI:

var fileUrl = NSUrl.CreateFileUrl(path, null);
if (fileUrl.GetResourceValue(out NSString utiValue, NSUrl.TypeIdentifierKey, out NSError error))
{
    var uti = UniformTypeIdentifiers.UTType.GetType(utiValue);
    return uti?.PreferredMimeType ?? "application/octet-stream";
}
return "application/octet-stream";

内容的提问来源于stack exchange,提问作者Huong Tran

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.04 21:52:33