.NET Maui中如何获取.mp4和.jpg文件的媒体创建日期?
获取.mp4和.jpg文件的媒体创建日期(.NET Maui)
由于文件副本的创建日期和实际媒体拍摄/生成日期不符,你需要读取文件的媒体元数据属性来获取正确的日期。以下是针对Windows平台的实现方案(如需跨平台可扩展其他平台代码):
实现步骤
1. 定义共享接口
在共享项目中创建接口,统一跨平台调用的契约:
namespace YourAppNamespace; public interface IMediaDateService { Task<DateTime?> GetMediaCreationDateAsync(string filePath); }
2. Windows平台具体实现
在Windows项目(WinUI)中创建服务类,利用Windows原生API读取媒体属性:
using Windows.Storage; using Windows.Storage.FileProperties; namespace YourAppNamespace.WinUI; public class MediaDateService : IMediaDateService { public async Task<DateTime?> GetMediaCreationDateAsync(string filePath) { try { var storageFile = await StorageFile.GetFileFromPathAsync(filePath); return storageFile.FileType.ToLower() switch { ".jpg" or ".jpeg" => (await storageFile.Properties.GetImagePropertiesAsync()).DateTaken, ".mp4" => (await storageFile.Properties.GetVideoPropertiesAsync()).DateTaken, _ => null }; } catch (Exception ex) { System.Diagnostics.Debug.WriteLine($"读取媒体日期失败: {ex.Message}"); return null; } } }
3. 注册服务
在MauiProgram.cs中注册平台特定服务:
using YourAppNamespace.WinUI; var builder = MauiApp.CreateBuilder(); builder .UseMauiApp<App>() .ConfigureFonts(fonts => { fonts.AddFont("OpenSans-Regular.ttf", "OpenSansRegular"); }); #if WINDOWS builder.Services.AddSingleton<IMediaDateService, MediaDateService>(); #endif return builder.Build();
4. 在业务代码中使用
通过依赖注入调用服务获取日期:
public class MediaViewModel { private readonly IMediaDateService _mediaDateService; public MediaViewModel(IMediaDateService mediaDateService) { _mediaDateService = mediaDateService; } public async Task LoadMediaDate(string filePath) { var mediaCreationDate = await _mediaDateService.GetMediaCreationDateAsync(filePath); if (mediaCreationDate.HasValue) { // 处理获取到的日期,例如绑定到UI Console.WriteLine($"媒体创建日期: {mediaCreationDate.Value:F}"); } else { // 处理无法读取的情况 } } }
关键注意事项
- 权限处理:如果访问应用沙盒外的文件,需要在Windows项目的
Package.appxmanifest中添加broadFileSystemAccess权限;更推荐使用文件选择器让用户主动选择文件,无需额外权限。 - 跨平台扩展:若需支持Android/iOS,可分别在对应平台实现
IMediaDateService:- Android:使用
android.media.ExifInterface读取图片/视频的Exif元数据 - iOS:使用
PHAsset或ImageIO框架获取媒体属性
- Android:使用
内容的提问来源于stack exchange,提问作者Colebam
相关产品推荐
相关产品推荐

