Exception When Creating Folder

0

I'm trying to save a bunch of files into a folder. That folder will already exist, but I want to completely delete it and its contents and save the new files into the folder. I'm using the following code:

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

However, I'm getting an exception the second time I try to do this:

Cannot create a file when that file already exists. (Exception from HRESULT: 0x800700B7)

Note that I can save once and it replaces the folder correctly. It's only when I try to do it a second time that it fails. It should be replacing the existing item on a collision so I suspect that I'm not releasing something correctly, but I've no idea what.

c#
file
uwp
inkcanvas
asked on Stack Overflow Jun 2, 2016 by RareNCool

1 Answer

0

Ah I found it! I replaced the stream-saving code with this:

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

and it now works fine.

Replacing await stream.FlushAsync() with stream.Dispose() also seems to do the trick.

answered on Stack Overflow Jun 2, 2016 by RareNCool

User contributions licensed under CC BY-SA 3.0