How to copy a file from Visual Studio project to UWP application's LocalFolder on build

我的未来我决定 提交于 2019-12-11 14:29:30

问题


I have a Xamarin solution with a UWP project in it. I cannot understand how to copy a file that is in my VS project to the UWP LocalFolder. I've tried fiddling with the file's Build Action (Compile, Content, Embedded Resource, AdditionalFiles) and I've tried to manually create this location.

Apparently this code:

Windows.Storage.StorageFolder appDataFolder = Windows.Storage.ApplicationData.Current.LocalFolder;

string fileName = (appDataFolder.Path + "\\HighScore.csv");

Creates this path:

'C:\Users\<my Name>\AppData\Local\Packages\ebf29fcf-0080-4b4c-b873-78fd1340811d_9tywq191txc1p\LocalState\HighScore.csv'

So I just need to figure out how to get the CSV file that's in my project to this LocalState folder. Any help appreciated.


回答1:


Firstly, add the .csv file to your assets folder and set the build action to Content.

After that, you can manually copy the file from Assets to your Local Folder at runtime with the following snippet.

var file = await StorageFile.GetFileFromApplicationUriAsync(new Uri("ms-appx:///Assets/HighScore.csv"));
 if (file != null)
 {
     // Copy .csv file to LocalFolder so we can read / write to it.
     // No CollisionOption will default to Fail if file already exists,
     // to copy every time the code is run, add NameCollisionOption.ReplaceExisting
     await file.CopyAsync(ApplicationData.Current.LocalFolder);

     // Get path of newly created file
     String newFile = ApplicationData.Current.LocalFolder.Path + "/HighScore.csv";
 }



回答2:


You could put in some code to copy it there:

// This would point to (in respect to your build platform target):
// C:\Users\User\Source\Repos\MyAwesomeApp\MyAwesomeApp.UWP\bin\x64\Debug\AppX
Uri uri = new Uri("ms-appx:///HighScores.csv");


// throws Exception if file doesn't exist
var file = await StorageFile.GetFileFromApplicationUriAsync(uri);


// copy the file to the package:
await file.CopyAsync(ApplicationData.Current.LocalFolder);

That's the jist of it. Hope it works for you.



来源:https://stackoverflow.com/questions/57139554/how-to-copy-a-file-from-visual-studio-project-to-uwp-applications-localfolder-o

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!