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
我做到了。在這種情況下,該文件不存在,並且應該創建它時引發拒絕訪問。我重新啓動了操作系統,運行了相同的代碼並且工作正常(瀏覽器窗口也打開並看到它創建)。作爲參考,它將文件存儲在C:\ Users \ *我的用戶名*] \ AppData \ Local \ Packages \ * guid * \ LocalState文件夾中。 –
由於之前的異常我沒有能夠重新創建它。我將在下次檢查文件句柄,並確保其他東西沒有保留它(或者以某種方式將句柄保持打開狀態)。 –
我有這個確切的問題 - 它是隨機的,只發生100次1或2。我的工作是,因爲微軟對無法提供回購的這個問題非常不屑,所以要創建文件的備份並捕獲異常並重寫該文件。不優雅,但我唯一的功能工作。 –