gpt4 book ai didi

c# - 如何关闭打开的StorageFile?

转载 作者:太空宇宙 更新时间:2023-11-03 10:22:20 26 4
gpt4 key购买 nike

我正在编写一个Windows Phone 8.1 (WINRT XAML) 应用

在方法 1 中,我打开一个 StorageFile,在方法 2 中,我在同一个文件上写入。但是它在写入文件时显示错误。

  1. 如何在打开并阅读内容后关闭此文件?
  2. 那么方法2写入后如何再次关闭这个文件呢?

    private async Task<bool> Method1(int workOutID)
    {
    string filename = "WorkoutOfflineDataFile.txt";
    StorageFolder LocalStorageFolderObject = ApplicationData.Current.LocalFolder;
    StorageFile StorageFileObject = await LocalStorageFolderObject.CreateFileAsync(filename, CreationCollisionOption.OpenIfExists);
    string JSONFromFile = await FileIO.ReadTextAsync(StorageFileObject);
    }

    private async void Method2()
    {
    string filename = "WorkoutOfflineDataFile.txt";
    StorageFolder LocalStorageFolderObject = ApplicationData.Current.LocalFolder;
    StorageFile StorageFileObject = await LocalStorageFolderObject.CreateFileAsync(filename, CreationCollisionOption.OpenIfExists);
    await FileIO.WriteTextAsync(StorageFileObject, JSonData_ToSave);
    }

ERROR:

Exception thrown: 'System.UnauthorizedAccessException' in mscorlib.ni.dll

Additional information: Access is denied. (Exception from HRESULT: 0x80070005 (E_ACCESSDENIED))

最佳答案

代码似乎是正确的,我认为异常是由其他东西抛出的。

无论如何,如果你想确保你的文件和流在读/写操作后关闭,你可以使用一次性方式:

private async Task<bool> Method1(int workOutID)
{
string filename = "WorkoutOfflineDataFile.txt";
StorageFolder LocalStorageFolderObject = ApplicationData.Current.LocalFolder;
StorageFile StorageFileObject = await LocalStorageFolderObject.CreateFileAsync(filename, CreationCollisionOption.OpenIfExists);
using (var stream = await StorageFileObject.OpenStreamForReadAsync())
{
using (var reader = new StreamReader(stream))
{
string JSONFromFile = reader.ReadToEnd();
}
}
}

private async void Method2()
{
string filename = "WorkoutOfflineDataFile.txt";
StorageFolder LocalStorageFolderObject = ApplicationData.Current.LocalFolder;
StorageFile StorageFileObject = await LocalStorageFolderObject.CreateFileAsync(filename, CreationCollisionOption.OpenIfExists);
using (var stream = await StorageFileObject.OpenStreamForWriteAsync())
{
using (var writer = new StreamWriter(stream))
{
writer.Write(JSonData_ToSave);
}
}
}

关于c# - 如何关闭打开的StorageFile?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32948609/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com