Search code examples
c#xamarin.formssystem.io.file

xamarin forms UWP app - after saving a file locally, sometimes it locks


Background Information

I have a c# xamarin forms application where I allow users to download files from Sharepoint. I'm saving the stream to a local folder on the windows desktop. Once the download is completed, I'd like for the users to be able to click on the file and open it. Currently, when I try to open the file, I get errors saying that the file is in use by another application or user.

The download itself seems to be working fine.

Here's the code:

 try
 {
      using (var stream = await App.GraphClient.Sites[TestSiteId].Drive.Items[listItemAsDriveItem.DriveItem.Id].Content.Request().GetAsync())
      {
         var driveItemPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), listItemAsDriveItem.DriveItem.Name);
         var driveItemFile = System.IO.File.Create(driveItemPath);
         stream.Seek(0, SeekOrigin.Begin);
         stream.CopyTo(driveItemFile);
         stream.Dispose();
      }
      DisplayAlert("Download", listItemAsDriveItem.DriveItem.Name + " successfully downloaded", "OK");
 }
 catch (Exception ex)
 {
      Console.WriteLine("Download failed with: " + ex.Message);
      DisplayAlert("Error", listItemAsDriveItem.DriveItem.Name + " failed with: " + ex.Message, "OK");
 }

What I've Tried

As you can see, I have everything wrapped inside a "using{}" statement. I'm also explicitly calling stream.Dispose(); I've also tried to replace the call to .Dispose with Close() but that doesn't make a diff either.


Solution

  • The problem is that driveItemFile is also a Stream, but it was not disposed/closed and it's the actual stream that creates and locks the file