如何在.NET Standard 2.0 DLL中访问文件?UWP场景问题求助
解决.NET Standard 2.0 DLL中访问Windows.Storage的问题
嘿,这个问题我之前帮不少开发者捋清楚过——核心卡点其实是.NET Standard的设计定位:它是一套跨平台的API规范,并不包含UWP专属的Windows Runtime API(比如Windows.Storage),所以你没法直接在.NET Standard 2.0 DLL里添加对它的程序集引用。不过有几个靠谱的解决方案,结合你的MVVM架构,我推荐优先用第二种:
方案1:通过条件编译+UWP项目引用实现平台特定调用
如果你的DLL只需要在UWP环境下运行,可以用条件编译来隔离UWP专属代码:
- 在.NET Standard项目的
.csproj文件中添加针对UWP Fall Creators Update(版本号uap10.0.16299)的条件引用:<ItemGroup Condition="'$(TargetFramework)' == 'uap10.0.16299'"> <PackageReference Include="Microsoft.NETCore.UniversalWindowsPlatform" Version="6.2.14" /> </ItemGroup> - 在代码中用编译指令包裹Windows.Storage的调用逻辑:
#if WINDOWS_UWP using Windows.Storage; public async Task<string> ReadAppFileAsync(string fileName) { var localFolder = ApplicationData.Current.LocalFolder; var file = await localFolder.GetFileAsync(fileName); return await FileIO.ReadTextAsync(file); } #endif
这样你的DLL在UWP项目中就能正常调用Windows.Storage,其他平台下这段代码会被自动忽略。
方案2:抽象接口+依赖注入(更符合MVVM解耦原则)
既然是MVVM架构,最好不要让.NET Standard DLL直接依赖UWP专属API,通过抽象层解耦会更优雅:
- 在.NET Standard项目中定义文件访问的抽象接口:
public interface IFileAccessService { Task<string> ReadTextFromFileAsync(string filePath); Task WriteTextToFileAsync(string filePath, string content); } - 在你的UWP项目中实现这个接口,这里就可以自由使用Windows.Storage了:
using Windows.Storage; public class UwpFileAccessService : IFileAccessService { public async Task<string> ReadTextFromFileAsync(string filePath) { var file = await StorageFile.GetFileFromPathAsync(filePath); return await FileIO.ReadTextAsync(file); } public async Task WriteTextToFileAsync(string filePath, string content) { var file = await StorageFile.GetFileFromPathAsync(filePath); await FileIO.WriteTextAsync(file, content); } } - 在MVVM的启动逻辑(比如
App.xaml.cs)中,将UwpFileAccessService注入到依赖容器,然后在.NET Standard的ViewModel中通过构造函数接收IFileAccessService来使用——全程不需要让DLL直接引用Windows.Storage,完美契合MVVM的解耦思想。
方案3:使用Windows Compatibility Pack
微软提供的Windows Compatibility Pack可以让.NET Standard项目访问部分Windows专属API,适合快速适配:
- 在.NET Standard项目中安装NuGet包:
Microsoft.Windows.Compatibility - 安装完成后即可直接引用
Windows.Storage,但要注意:Fall Creators Update(1709)对部分API的支持有限,建议先测试核心文件操作是否正常。
内容的提问来源于stack exchange,提问作者Vivek Verma
相关产品推荐
相关产品推荐

