0

I have written a windows service to move a file from one location to another and,

then read the file in the new location and write the data to the database.

In the middle of the execution there is an error message:

IOException: The process cannot access the file 'file path' because it is being used by another process.

My code:

File move class

  public void mysql()
        {
            string fileName = "Bargstedt.csv";
            string sourcePath = @"\\192.168.1.2\Data\Company Files\";

            string targetPath = @"C:\Users\source";


            string sourceFile = System.IO.Path.Combine(sourcePath, fileName);
            string destFile = System.IO.Path.Combine(targetPath, fileName);


            if (!System.IO.Directory.Exists(targetPath))
            {
                System.IO.Directory.CreateDirectory(targetPath);
            }
              System.IO.File.Copy(sourceFile, destFile, true);

            if (System.IO.Directory.Exists(sourcePath))
            {

                string[] files = System.IO.Directory.GetFiles(sourcePath);

                    fileName = System.IO.Path.GetFileName(fileName);
                    destFile = System.IO.Path.Combine(targetPath, fileName);
                    FileInfo info = new FileInfo(destFile);
                    bool exists = info.Exists;
                    if (exists == true)
                    {
                        try
                      {
                           int delay = 400;

                       File.Delete(@"C:\Users\Isuruh\source\Bargstedt.csv");
                            Thread.Sleep(delay); 
                         System.IO.File.Copy(sourceFile, destFile, true);
                        Debug.WriteLine("file moved");

                      }
                        catch (IOException ex) { }


                    }

                 }
            else
            {
                Console.WriteLine("Source path does not exist!");
            }
            Console.WriteLine("Press any key to exit.");
            }

Insert Class

public void Insert()
        {
                if (this.OpenConnection() == true)
                {
                      using(var reader = new StreamReader(@"C:\Users\source\Bargstedt.csv"))
                      //using (var stream = File.Open(path, FileMode.Open, FileAccess.Write, FileShare.ReadWrite))
                    {
                        List<string> listA = new List<string>();

                        while (!reader.EndOfStream)
                        {
                            var line = reader.ReadLine();
                            var values = line.Split(',');
                            string querynew = "INSERT INTO new_jobs"
                                      + "(board_code,status,code,no1,no2,thickness,dimension,material,root,variable,number,stable,constant)" 
                                      + "VALUES (?jobNo, ?strClientName, ?strClientReference, ?strJobCategory, ?datCommisioned, ?datPromisedDelivery, ?division, ?date_assigned, ?root, ?variable, ?number, ?stable, ?constant)";

I did not mention the whole code for the service since it's too lengthy.

As given in Solution 01 I tried to use,

using (var stream = File.Open(path, FileMode.Open, FileAccess.Write, FileShare.Read))

line instead of

 using(var reader = new StreamReader(@"C:\Users\source\Bargstedt.csv"))

But that triggers errors in the below keywords I have used.

I am not sure is it possible to use a file open instead of a reader class?

Basically, what I need to do is start the Insert process after completing the file move process.

Any suggestions on how to do that?

PS: This is possibly a duplicate question of the question I have mentioned above. I tried my very best to make this question unique. Appreciate if not marked as duplicate. Thank you!

jazb
  • 5,498
  • 6
  • 37
  • 44
Simon
  • 195
  • 2
  • 4
  • 18
  • 2
    You do not properly dispose of the FileHandle. Filehandles and network connections are the classical examples of unmanaged resources that need disposing. Ideally use the using block to get rid of them reliably. – Christopher Nov 22 '18 at 02:36
  • @Adriano Repetti any thoughts? – Simon Nov 22 '18 at 02:43
  • Where is the exception thrown? I'm going to guess that unstated part of this story is that there is another process that writes the file in the original location and that this service is supposed to grab it when it's done. Is that right? – Tom Blodget Nov 22 '18 at 02:55
  • There ain't any other process to "write the file in the original location (in your words)". Only the file move class which move the csv from original location to the new location. That's it! @Tom Blodget – Simon Nov 22 '18 at 03:02
  • the whole you first code sample can be replaced with `File.Move(sourceFile, destFile)` – vasily.sib Nov 22 '18 at 03:12
  • your second code sample is not complete, but I bet it can be replaced with: `foreach (var line in File.ReadLines(@"C:\Users\source\Bargstedt.csv")) { ... }`. No need for any `Stream` or `StreamReader`. – vasily.sib Nov 22 '18 at 03:16
  • Were exactly (on which line) do you get the exception? – Klaus Gütter Nov 22 '18 at 04:46

0 Answers0