【发布时间】: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