2016-03-11 54 views
1

我想写的文字内容到位于Assets文件夹中的文件,所以我访问文件,但我没有访问写进去,我的代码是:写入从资产文件夹UWP文件

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

不得不提的,我需要改变这个文件,因为应用程序的情况下,也或许是有办法创造公共app文件夹这个文件,然后将它资产。

回答

7

位于Assets文件夹中的文件是read only这就是为什么你会得到这个例外。就像您在最后提到的那样,有一种方法可以在公共位置创建文件,将所需内容写入其中,然后将文件移动到资产文件夹中。它会像:

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

      } 
+0

是的,这是工作得很好 – Choletski

相关问题