将字符串添加到文件内容

时间:2017-01-21 19:54:08

标签: vb.net file uwp

我尝试打开一个文件,并通过UWP中的以下代码将字符串添加到现有内容中

Public Async Sub AddDataToFile(sFileName As String, sStructData As String)
    Dim storageFolder As StorageFolder = Windows.Storage.ApplicationData.Current.LocalFolder
    Dim sampleFile As StorageFile = Await storageFolder.GetFileAsync(sFileName)

    Dim text As String = Await Windows.Storage.FileIO.ReadTextAsync(sampleFile)
    text += sStructData
    Await Windows.Storage.FileIO.WriteTextAsync(sampleFile, text)

End Sub

不幸的是我抛出了一个异常:

  

mscorlib.ni.dll中出现“System.UnauthorizedAccessException”类型的异常,但未在用户代码中处理。

方法ReadTextAsync()。为什么?

2 个答案:

答案 0 :(得分:0)

  Windows.Storage.StorageFile fileToRead =
                    await storageFolder.GetFileAsync("File.txt");
                    string text = await Windows.Storage.FileIO.ReadTextAsync(fileToRead);

                        await Windows.Storage.FileIO.WriteTextAsync(fileToRead, "text Goes HERE" + text );

我认为这就是你需要的

答案 1 :(得分:0)

我已经测试了你的代码片段并且效果很好。您的AddDataToFile方法没有任何问题。因此,可能的原因可能是您为读取而调用的文件有问题。由于您可以GetFileAsync成功,因此该文件可能实际存在。然后你在System.UnauthorizedAccessException方法获得了ReadTextAsync(),这可能是因为你没有权限访问这个文件,也许这个文件是由你无法访问的其他用户创建的,或者文件是由另一个写作过程。

您可以自己在本地文件夹中创建一个文件并再次读写,它应该可以正常工作。由于您没有提供用于调用此方法的代码,因此我在此处完成了使用新创建的文件调用该方法的代码,并且它可以正常工作。代码如下:

Private Async Sub btnreadandwrite_Click(sender As Object, e As RoutedEventArgs)
    Dim storageFolder As StorageFolder = Windows.Storage.ApplicationData.Current.LocalFolder
    Dim sampleFile As StorageFile = Await storageFolder.CreateFileAsync("sampleFile.txt", CreationCollisionOption.ReplaceExisting)
    Await FileIO.WriteTextAsync(sampleFile, "inital text")
    AddDataToFile("sampleFile.txt", "add new content")
End Sub

Public Async Sub AddDataToFile(sFileName As String, sStructData As String)
    Dim storageFolder As StorageFolder = Windows.Storage.ApplicationData.Current.LocalFolder
    Dim sampleFile As StorageFile = Await storageFolder.GetFileAsync(sFileName)
    Dim text As String = Await Windows.Storage.FileIO.ReadTextAsync(sampleFile)
    text += sStructData
    Await Windows.Storage.FileIO.WriteTextAsync(sampleFile, text)
End Sub