2012-08-30 70 views
4

我想写一些代码写入文本文件。我有代码工作......但今天(没有改变)它开始产生一个“访问被拒绝”的错误。我正在写入LocalFolder(Windows.Storage.ApplicationData.Current.LocalFolder)。WinRT - 访问被拒绝读取文件

我是否必须在清单中声明我想要将文件保存在LocalStorage中?我知道我必须为我的文档,或者我错过了什么?这里是我的样品的方法,说明如何,我想写出一个文件:

 ''' <summary> 
    ''' Writes all of the text to the specified file in one of the specified safe storage folders. 
    ''' </summary> 
    ''' <param name="text">The text to write.</param> 
    ''' <param name="append">Whether or not to append the data or overwrite what is in the file.</param> 
    ''' <param name="fileName">The name of the file to write the data to.</param> 
    ''' <param name="safeFolder">The safe storage folder that should be written to. These folders are isolated for the application to use 
    ''' and do not require additional manifest permissions.</param> 
    ''' <returns></returns> 
    ''' <remarks></remarks> 
    Public Shared Async Function WriteAllText(text As String, append As Boolean, fileName As String, safeFolder As SafeStorageFolder) As Task 
     Dim folder As Windows.Storage.StorageFolder 

     Select Case safeFolder 
      Case SafeStorageFolder.Local 
       folder = Windows.Storage.ApplicationData.Current.LocalFolder 
      Case SafeStorageFolder.Roaming 
       folder = Windows.Storage.ApplicationData.Current.RoamingFolder 
      Case SafeStorageFolder.Temp 
       folder = Windows.Storage.ApplicationData.Current.TemporaryFolder 
      Case Else 
       folder = Windows.Storage.ApplicationData.Current.LocalFolder 
     End Select 

     Dim sf As StorageFile 

     If append = True Then 
      sf = Await folder.CreateFileAsync(fileName, Windows.Storage.CreationCollisionOption.OpenIfExists) 
     Else 
      sf = Await folder.CreateFileAsync(fileName, Windows.Storage.CreationCollisionOption.ReplaceExisting) 
     End If 

     ' WriteTextAsync will always overwrite the file even if the existing file has been opened. We'll use 
     ' AppendTextAsync here, the above CreateFileAsync will handle whether the file has been truncated or not. 
     Await FileIO.AppendTextAsync(sf, text) 

    End Function 

回答

2

我用你有相同的代码逻辑在测试项目,它为我工作得很好。我没有浏览所有的追加/不追加路径,但是我可以写入每个文件夹。

您是否从您在select中设置的文件夹对象中提取了文件路径,并仔细检查是否可以在文件资源管理器中打开它?

+0

我做到了。在这种情况下,该文件不存在,并且应该创建它时引发拒绝访问。我重新启动了操作系统,运行了相同的代码并且工作正常(浏览器窗口也打开并看到它创建)。作为参考,它将文件存储在C:\ Users \ *我的用户名*] \ AppData \ Local \ Packages \ * guid * \ LocalState文件夹中。 –

+0

由于之前的异常我没有能够重新创建它。我将在下次检查文件句柄,并确保其他东西没有保留它(或者以某种方式将句柄保持打开状态)。 –

+0

我有这个确切的问题 - 它是随机的,只发生100次1或2。我的工作是,因为微软对无法提供回购的这个问题非常不屑,所以要创建文件的备份并捕获异常并重写该文件。不优雅,但我唯一的功能工作。 –