从资产文件夹 uwp 写入文件 [英] Write into file from assets folder uwp

查看:36
本文介绍了从资产文件夹 uwp 写入文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将文本内容写入位于 Assets 文件夹的文件中,因此我访问文件但我无权写入文件,我的代码是:

I'd like to write text content into a file that is located Assets folder, so I access file but I don't have access to write into it, my code is:

    try {
            //get the file
            StorageFile storageFile = await StorageFile.GetFileFromApplicationUriAsync(new Uri("ms-appx:///assets/test.txt"));

            //try to write sring to it
            await FileIO.WriteTextAsync(storageFile, "my string");

            } catch (Exception ex) {
            Debug.WriteLine("error: " + ex);

            }

然后我收到错误:

    Exception thrown: 'System.UnauthorizedAccessException' in mscorlib.ni.dll
error: System.UnauthorizedAccessException: Access is denied. (Exception from HRESULT: 0x80070005 (E_ACCESSDENIED))
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.GetResult()
   at MyProject.MainPage.<overWriteHtmlSrcFile>d__6.MoveNext()

不得不提的是,由于应用场景,我需要更改此文件,或者有没有办法在公共应用文件夹中创建此文件,然后将其移动到资产中.

Have to mention that I need to change this file due app scenario, or maybe is there a way to create this file in public app folder and then move it in assets.

推荐答案

位于 Assets 文件夹中的文件是只读,这就是您收到此异常的原因.就像你在最后提到的那样,有一种方法可以在公共位置创建文件,将所需内容写入其中,然后将文件移动到资产文件夹中.它会像:

Files located into Assets folder are read only that's why you get this exception. Like you mentioned at the end, there is a method to create your file in a public location, write what you need into it and then just move the file in assets folder. It will be like:

 try {
            //create file in public folder
            StorageFolder storageFolder = ApplicationData.Current.LocalFolder;
            StorageFile sampleFile = await storageFolder.CreateFileAsync("test.txt", CreationCollisionOption.ReplaceExisting);

            //write sring to created file
            await FileIO.WriteTextAsync(sampleFile, htmlSrc);

            //get asets folder
            StorageFolder appInstalledFolder = Windows.ApplicationModel.Package.Current.InstalledLocation;
            StorageFolder assetsFolder = await appInstalledFolder.GetFolderAsync("Assets");

            //move file from public folder to assets
            await sampleFile.MoveAsync(assetsFolder, "new_file_name.txt", NameCollisionOption.ReplaceExisting);

            } catch (Exception ex) {
            Debug.WriteLine("error: " + ex);

            }

这篇关于从资产文件夹 uwp 写入文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆