首页 文章

创建文件夹时出现异常

提问于
浏览
0

我正在尝试将一堆文件保存到文件夹中 . 该文件夹已存在,但我想完全删除它及其内容并将新文件保存到该文件夹中 . 我正在使用以下代码:

Project project;        //This is a parameter handed in when the method is called
List<InkStrokeContainer> containers;      //This is a parameter handed in when the method is called

var projectFolder = await ApplicationData.Current.LocalFolder.GetFolderAsync(project.Id.ToString());
var slidesFolder = await projectFolder.CreateFolderAsync("Slides", CreationCollisionOption.ReplaceExisting);

StorageFile file;
IRandomAccessStream stream;

for (int i = 0; i < containers.Count; i++)
{
    if (containers[i].GetStrokes().Count > 0)
    {
        file = await slidesFolder.CreateFileAsync($"{i.ToString()}.jpg", CreationCollisionOption.ReplaceExisting);
        stream = await file.OpenAsync(FileAccessMode.ReadWrite);
        await containers[i].SaveAsync(stream);
        await stream.FlushAsync();
    }
}

但是,我第二次尝试这样做时遇到异常:

当该文件已存在时,无法创建文件 . (HRESULT异常:0x800700B7)

请注意,我可以保存一次,它会正确替换文件夹 . 只有当我第二次尝试它失败时才会这样做 . 它应该是在碰撞时替换现有项目,所以我怀疑我没有正确发布,但我不知道是什么 .

1 回答

  • 0

    啊我找到了!我用这个替换了流节省代码:

    using (var stream = await file.OpenAsync(FileAccessMode.ReadWrite))
        await containers[i].SaveAsync(stream);
    

    它现在工作正常 .

    stream.Dispose() 替换 await stream.FlushAsync() 似乎也可以解决问题 .

相关问题