无法写入文本文件

时间:2014-04-29 18:55:06

标签: c# visual-studio-2012 windows-runtime

我正在尝试写入我项目中的文件夹中的txt文件,但我不能因某些原因抛出异常,我已尝试过所有内容但仍无法正常工作

// settings
    // same as (ms-appx:///MyFolder/MyFile.txt)
    var _Folder = Windows.ApplicationModel.Package.Current.InstalledLocation;
    _Folder = await _Folder.GetFolderAsync("MyFolder");

    // acquire file
    var _File = await _Folder.GetFileAsync("MyFile.txt");
    Assert.IsNotNull(_File, "Acquire File");

    // write content
    var _WriteThis = "Hello World";
    //  Error here
    await Windows.Storage.FileIO.WriteTextAsync(_File, _WriteThis);

以下是我在使用错误的代码,当我想写入文件时发生错误

这是例外

System.UnauthorizedAccessException was unhandled
  HResult=-2147024891
  Message=Access is denied. (Exception from HRESULT: 0x80070005 (E_ACCESSDENIED))
  Source=mscorlib
  StackTrace:
       at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
       at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
       at System.Runtime.CompilerServices.TaskAwaiter.GetResult()
       at ManipulatingTxtFiles.MainPage.<addBtn_Click>d__a.MoveNext() in c:\Users\Tunde\Documents\Visual Studio 2012\Projects\ManipulatingTxtFiles\ManipulatingTxtFiles\MainPage.xaml.cs:line 115
    --- End of stack trace from previous location where exception was thrown ---
       at System.Runtime.CompilerServices.AsyncMethodBuilderCore.<ThrowAsync>b__0(Object state)
       at System.Threading.WinRTSynchronizationContext.Invoker.InvokeCore()
    --- End of stack trace from previous location where exception was thrown ---
       at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
       at System.Threading.WinRTSynchronizationContext.Invoker.<InvokeCore>b__0(Object o)
       at System.Threading.QueueUserWorkItemCallback.WaitCallback_Context(Object state)
       at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
       at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
       at System.Threading.QueueUserWorkItemCallback.System.Threading.IThreadPoolWorkItem.ExecuteWorkItem()
       at System.Threading.ThreadPoolWorkQueue.Dispatch()
       at System.Threading._ThreadPoolWaitCallback.PerformWaitCallback()
  InnerException: 

1 个答案:

答案 0 :(得分:3)

您的包文件夹及其所有内容(即从Windows.ApplicationModel.Package.Current.InstalledLocation,ms-appx:///或ms-appx-web:///引用的任何内容都是只读的。因此,访问被拒绝的例外。

请改用Windows.Storage.ApplicationData.LocalFolder或TemporaryFolder(参见http://msdn.microsoft.com/en-us/library/windows/apps/xaml/windows.storage.applicationdata.aspx),也可以使用ms-appdata:/// local /或ms-appdata:/// temp /来完成。这些位置是可读写的。