Search code examples
c#uwpinkcanvas

Save InkCanvas strokes without using SaveFileDialog (UWP)


In my UWP C# app I'm trying to save the strokes of an InkCanvas in a way that the user should be able to load the file and continue editing the strokes, is it possible to do this without asking the user to choose a location but rather by saving the file to a default location?

Thanks in advance


Solution

  • You should create a file in the AppData Local folder of your app and read it when necessary. I suggest using this code to create the file:

    Windows.Storage.StorageFolder storageFolder = Windows.Storage.ApplicationData.Current.LocalFolder;
    Windows.Storage.StorageFile file = await storageFolder.CreateFileAsync("sample.gif", Windows.Storage.CreationCollisionOption.ReplaceExisting);
    

    And this one to write the strokes on it:

    Windows.Storage.CachedFileManager.DeferUpdates(file);
    IRandomAccessStream stream = await file.OpenAsync(Windows.Storage.FileAccessMode.ReadWrite);
    using (IOutputStream outputStream = stream.GetOutputStreamAt(0)) {
       await inkCanvas.InkPresenter.StrokeContainer.SaveAsync(outputStream);
       await outputStream.FlushAsync();
    }
    stream.Dispose();
    
    Windows.Storage.Provider.FileUpdateStatus status = await Windows.Storage.CachedFileManager.CompleteUpdatesAsync(file);
    
    if (status == Windows.Storage.Provider.FileUpdateStatus.Complete) {
         // File saved
    } else {
         // File NOT saved
    }