0

它不会每次都抛出这个错误,这就是它奇怪的原因。我有 50% 的机会成功。

这就是我调用保存方法的方式

private async void btnSave_Click(object sender, RoutedEventArgs e)
{
    await settings.WriteSettings(settings);
}

这就是方法本身

public async Task WriteSettings(Settings settings)
{
    var ser = new System.Xml.Serialization.XmlSerializer(typeof(Settings));
    var writer = new StringWriter();
    ser.Serialize(writer, settings);
    dom.LoadXml(writer.ToString());
    StorageFolder sf = ApplicationData.Current.LocalFolder;
    StorageFile st;
    st = await sf.CreateFileAsync(filename, CreationCollisionOption.ReplaceExisting); // here i get the error
    await dom.SaveToFileAsync(st);
}

我希望你们理解这个问题,你可以帮助我找到解决方案

4

1 回答 1

1

当我尝试多次访问文件时,我得到了访问被拒绝的原因。这是因为我使用后没有关闭文件。

这就是我现在访问文件的方式:

public static async Task WriteSettings(Settings settings)
    {
        StorageFile file = await ApplicationData.Current.RoamingFolder.CreateFileAsync(filename, CreationCollisionOption.ReplaceExisting);
        var stream = await file.OpenStreamForWriteAsync();

        var ser = new XmlSerializer(typeof(Settings));
        ser.Serialize(stream, settings);

        await stream.FlushAsync(); // This
        stream.Dispose(); // And this helped me solve my problem
    } 
于 2012-12-14T12:50:37.337 回答