且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在 UWP 中部署文件

更新时间:2023-11-17 22:51:22

您可以将文件作为资源或内容文件添加到您的项目中.如果文件类似于图像、SQLite 数据库或文本文件,***的方法是 Content 构建操作.

You can add files either as resources or content files to your project. If the file is something like a Image, SQLite Database or text file, the best approach will be the Content build action.

然后您可以使用 StorageFile.GetFromApplicationUriAsync 访问该文件:

You can then access the file using StorageFile.GetFromApplicationUriAsync:

var storeLogoFile = StorageFile.GetFromApplicationUriAsync( 
        new Uri( "ms-appx:///Assets/StoreLogo.png" ) );

如果您喜欢使用 System.IO,也可以获取 Path 本身:

You can also get the Path itself if your prefer to use System.IO:

var packagePath = Package.Current.InstalledLocation;
var filePath = Path.Combine( packagePath, "Assets/StoreLogo.png" );
//do something with the file

然而,这种方法仅在您只需要读取文件时才有效.如果您还需要修改它,则必须先将其复制到ApplicationData.Current.LocalFolder:

This approach however works only if you only need to read the file. If you also need to modify it, you will have to copy it to ApplicationData.Current.LocalFolder first:

var applicationDataFileCopy = 
     storeLogoFile.CopyAsync( ApplicationData.Current.LocalFolder );

您可能只想执行一次此操作,因此您可以先检查该文件是否已存在于 ApplicationData 中,然后再继续.

You might want to do this only once, so you can first check if the file already exists in ApplicationData before proceeding.