如何关闭打开的StorageFile

本文关键字:StorageFile 何关闭 | 更新日期: 2023-09-27 18:15:59

我正在写一个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);
    }
    
错误:

抛出异常:'System. 'UnauthorizedAccessException"mscorlib.ni.dll

附加信息:Access is denied。(来自HRESULT的例外:0 x80070005 (E_ACCESSDENIED))

如何关闭打开的StorageFile

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

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

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);
        }
    }
}

Festyk的解决方案有效吗?或许可以试着使用:

StorageFile StorageFileObject = await LocalStorageFolderObject.GetFileAsync(filename);

在你的第二个方法中,如果你确定file已经存在——记住,否则它会抛出一个异常。

你正在锁定method1()中的文件

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);
}

当你试图访问workoutofflinedataffile .txt时,你实际上锁定了这个文件,所以没有其他线程可以触摸它,直到它关闭。

卢卡的回答似乎是好的和安全的。