c# - 进程无法访问文件,因为它被另一个进程使用
问题描述
所以我收到异常“进程无法访问文件,因为它被另一个进程使用。
当我调用此特定方法时,将显示异常:
public async static Task<bool> DownloadFileFromFTP(string PathToFile, string AppName)
{
return await Task.Run(() => {
if (File.Exists("settings.xml"))
{
XmlSerializer xs = new XmlSerializer(typeof(Information));
FileStream read = new FileStream("settings.xml", FileMode.Open, FileAccess.Read, FileShare.Read);
Information info = (Information)xs.Deserialize(read);
try
{
FtpClient client = new FtpClient(info.HDSynologyIP);
string a = info.FtpPassword;
string FTPPassword = EncryDecryptor.Decrypt(a);
client.Credentials = new NetworkCredential(info.FtpUsername, FTPPassword);
client.Connect();
bool finish = client.DownloadFile(@info.Downloads + "\\" + AppName, PathToFile, FtpLocalExists.Overwrite, FluentFTP.FtpVerify.Retry);
if (finish == true)
{
client.Disconnect();
read.Close();
return true;
}
else
{
client.Disconnect();
read.Close();
return false;
}
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
read.Close();
}
read.Close();
}
else
{
MessageBox.Show("Missing settings.xml file");
return false;
}
return false;
});
}
并像这样在另一个类中调用它:
await General_Functions.DownloadFileFromFTP("Ultra_Script/Basic_SW/Adobe_Reader.exe", "Adobe_Reader.exe");
之前它不是异步的,但我不得不将它改造成异步方法。但我认为我正确地关闭了读者和客户。可能是异步方法的问题吗?因为在我让它异步之前我没有这个问题。
有人可以解释我做错了什么吗?
请注意,我使用FluentFTP
的是https://github.com/robinrodricks/FluentFTP。
解决方案
使用 using 终止文件阅读器进程
using(FileStream read = new FileStream("settings.xml", FileMode.Open, FileAccess.Read, FileShare.Read))
{
// your code here.....
}
推荐阅读
- c# - 如何在订阅中启用 RequiresSession 属性
- r - 理解 R 中 try 的行为
- c# - C# virtual 的 Visual Basic 等效项是什么
- docker - CentOS 上的 TensorFlow Docker 映像
- c# - 在 C# 应用程序中收到编组结构后不久堆损坏
- git - 在jenkins中禁用项目会停止wehbhoot触发器吗?
- powershell - 多个 Get-WmiObject 调用的单一连接
- swift - ARSCNView 在 iOS 12 上因 GPU 错误“命令缓冲区的执行被中止...(IOAF 代码 5)”而滞后
- julia - Julia:“<:”符号是什么意思?
- hugo - 为什么我的 Hugo 站点在部署到 Netlify 时不显示?