win-universal-app - 从 Assets 文件夹 uwp 写入文件

标签 win-universal-app

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

    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()

不得不提一下,由于应用场景,我需要更改此文件,或者是否有办法在公共(public)应用文件夹中创建此文件,然后将其移动到 Assets 中。

最佳答案

位于 Assets 文件夹中的文件是 只读 这就是你得到这个异常的原因。就像你最后提到的那样,有一种方法可以在公共(public)位置创建文件,将你需要的内容写入其中,然后将文件移动到 assets 文件夹中。它会是这样的:

 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);

            }

关于win-universal-app - 从 Assets 文件夹 uwp 写入文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35936725/

相关文章:

c# - ListView 项中的多个文本项

windows-phone-8 - 当我的 WP8 应用程序使用本地 linq to sql 数据库时,如何将其迁移到通用版本?

c# - UWP 等同于用于序列化 XAML 的 XamlWriter

c# - 异常 服务器违反了协议(protocol)。部分=响应状态行

Windows 10 蓝牙 Gatt 客户端 ValueChanged 问题

c# - 屏幕较小时增大字体大小

c# - 检查 MediaElement 是否有 Source

c++ - 如何使用 C++ 在 Windows 10 中更新事件磁贴

c# - 将 System.Speech.Synthesis 与 Windows10 通用应用程序 (XAML-C#) 结合使用

xaml - 如何使用 XAML 在 UWP 应用程序中创建默认按钮?