首页 > 解决方案 > 进程无法访问文件,因为它被另一个进程使用

问题描述

所以我收到异常“进程无法访问文件,因为它被另一个进程使用。

当我调用此特定方法时,将显示异常:

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

标签: c#asynchronousdisposefluentftp

解决方案


使用 using 终止文件阅读器进程

using(FileStream read = new FileStream("settings.xml", FileMode.Open, FileAccess.Read, FileShare.Read))
{ 
    // your code here.....
}

推荐阅读