从资产文件夹 uwp 写入文件



我想将文本内容写入位于文件夹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()

不得不提到的是,由于应用程序方案,我需要更改此文件,或者是否有办法在公共应用程序文件夹中创建此文件,然后将其移动到资产中。

位于Assets文件夹中的文件read only这就是您出现此异常的原因。就像您在最后提到的,有一种方法可以在公共位置创建文件,将所需的内容写入其中,然后将文件移动到 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);
            }

最新更新