0

So I'm getting exception "Process cannot access file because its used by another process.

The exception will show when i call this particular method:

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

And call it in another class like this:

await General_Functions.DownloadFileFromFTP("Ultra_Script/Basic_SW/Adobe_Reader.exe", "Adobe_Reader.exe");   

It wasn't asynchronous before but i had to remake it into asynchronous method. But i think I'm closing reader and client correctly. Can it be problem of async method? Because i don't had this problem before i made it asynchronous.

Can someone explain what I'm doing wrong?

Note, I am using FluentFTP from https://github.com/robinrodricks/FluentFTP .

mjwills
  • 23,389
  • 6
  • 40
  • 63
Johny Corbie
  • 63
  • 10

1 Answers1

0

use using to terminate the file reader process

using(FileStream read = new FileStream("settings.xml", FileMode.Open, FileAccess.Read, FileShare.Read))
{ 
    // your code here.....
}
Ahmad Alkaraki
  • 106
  • 1
  • 6