【问题标题】:xamarin forms UWP app - after saving a file locally, sometimes it locksxamarin 形成 UWP 应用程序-在本地保存文件后,有时它会锁定
【发布时间】:2021-10-14 18:13:43
【问题描述】:

背景信息

我有一个 c# xamarin 表单应用程序,允许用户从 Sharepoint 下载文件。我将流保存到 Windows 桌面上的本地文件夹中。下载完成后,我希望用户能够单击文件并打开它。目前,当我尝试打开文件时,我收到错误消息,提示该文件正在被其他应用程序或用户使用。

下载本身似乎运行良好。

代码如下:

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

我的尝试

如您所见,我将所有内容都包含在“using{}”语句中。 我也明确地调用了 stream.Dispose(); 我也尝试用 Close() 替换对 .Dispose 的调用,但这也不会产生差异。

【问题讨论】:

  • driveItemFile 也是一个 Stream,但它没有被释放/关闭。
  • 您不需要对作为using 语句的一部分创建的资源调用Dispose()
  • 我相信@JuanSturla 已经指出了你的实际错误:将driveItemFile = ... 包装在using 语句中,就像你的using (var stream = ....) 一样,文件不应该被锁定。
  • 是的,我赞成 @JuanSturla 的评论,因为他的评论为我解决了这个问题。如果你把它作为一个答案,我可以接受它
  • @dot 效果很好!我做了一个答案

标签: c# xamarin.forms system.io.file


【解决方案1】:

问题是driveItemFile 也是一个流,但它没有被释放/关闭,它是创建和锁定文件的实际流

【讨论】:

    【解决方案2】:

    您是否尝试过使用FileStream

    try
    {
        var driveItemPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), listItemAsDriveItem.DriveItem.Name);
        using (var stream = await App.GraphClient.Sites[TestSiteId].Drive.Items[listItemAsDriveItem.DriveItem.Id].Content.Request().GetAsync())
        using (var fs = new FileStream(driveItemPath, FileMode.Create, FileAccess.Open))
        {
            var driveItemFile = System.IO.File.Create(driveItemPath);
            stream.Seek(0, SeekOrigin.Begin);
            stream.CopyTo(fs);
        }
        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");
    }
    

    【讨论】:

      猜你喜欢
      • 2020-08-13
      • 2015-05-23
      • 1970-01-01
      • 2019-06-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多