简体   繁体   中英

The file cannot be accessed because it is being used by another process c#

I have written a windows service to copy a CSV file from an original location to a new location.

Afterward, the CSV in the new location has been read and write the data to MySQL.

The above tasks used to be run as 2 separate services since the file moving service triggers an error:

{"The process cannot access the file 'C:\\data.csv' because it is being used by another process."}

Consequently, I decided to merge the 2 services into 1 but still I got the same issue.

My code is as follows.

program.cs

   public void Insert()
        {
                if (this.OpenConnection() == true)
                {
                      using(var reader = new StreamReader(@"C:\data.csv"))
                    {
                        List<string> listA = new List<string>();

                        while (!reader.EndOfStream)
                        {
                            var line = reader.ReadLine();
                            var values = line.Split(',');
                            string querynew = "INSERT INTO new_jobs"
                                      + "(job_reference,status)" 
                                      + "VALUES (?jobNo, ?strClientName)";

                                MySqlCommand cmd = connection.CreateCommand();
                        cmd.CommandText= querynew;
                                cmd.Parameters.Add("?jobNo", MySqlDbType.VarChar).Value = (values[0]);
                                cmd.Parameters.Add("?strClientName", MySqlDbType.VarChar).Value =(values[1]);

                        cmd.ExecuteNonQuery(); 
                       56 filemove(); <-- error trigger line
                        }
                    }
                    this.CloseConnection();
                }

// file move function

 public void filemove()
            {
                string fileName = "data.csv";
               string sourcePath = @"\\Data\Company Files\";

                string targetPath = @"C:";

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

          //I won't include the whole code in this method since it's too lengthy.



            }

Service.cs

I do not include the rest of the code inside the methods.

void timer1_Tick(object sender, ElapsedEventArgs e)
        {

               dbConnect.Truncate();
                dbConnect.Insert();
                dbConnect.filemove();
        }

  protected override void OnStart(string[] args)
        {
            dbConnect.Insert();
            dbConnect.filemove();
        }

The error triggers in the line 56 inside Insert() method.

First close your connection and then call.

    public void Insert()
    {
            if (this.OpenConnection() == true)
            {
                  using(var reader = new StreamReader(@"C:\data.csv"))
                {
                    List<string> listA = new List<string>();

                    while (!reader.EndOfStream)
                    {
                        var line = reader.ReadLine();
                        var values = line.Split(',');
                        string querynew = "INSERT INTO new_jobs"
                                  + "(job_reference,status)" 
                                  + "VALUES (?jobNo, ?strClientName)";

                            MySqlCommand cmd = connection.CreateCommand();
                    cmd.CommandText= querynew;
                            cmd.Parameters.Add("?jobNo", MySqlDbType.VarChar).Value = (values[0]);
                            cmd.Parameters.Add("?strClientName", MySqlDbType.VarChar).Value =(values[1]);

                    cmd.ExecuteNonQuery(); 

                    }
                }
                this.CloseConnection();
                filemove();
            }

It's not clear what's happening within the filemove() method to trigger the error, it's probably further down in the part that wasn't included. That being said, you may try moving the call to filemove() after the using block of the StreamReader (as shown below). With it in the using block the StreamReader still has the file open and may restrict what's going on in filemove().

public void Insert()
{
    if (this.OpenConnection() == true)
    {
        using(var reader = new StreamReader(@"C:\data.csv"))
        {
            List<string> listA = new List<string>();

            while (!reader.EndOfStream)
            {
                var line = reader.ReadLine();
                var values = line.Split(',');
                string querynew = "INSERT INTO new_jobs"
                    + "(job_reference,status)" 
                    + "VALUES (?jobNo, ?strClientName)";

                MySqlCommand cmd = connection.CreateCommand();
                cmd.CommandText= querynew;
                cmd.Parameters.Add("?jobNo", MySqlDbType.VarChar).Value = values[0]);
                cmd.Parameters.Add("?strClientName", MySqlDbType.VarChar).Value = (values[1]);
                cmd.ExecuteNonQuery(); 
            }
        }
        filemove(); // move this here after the using block
        this.CloseConnection();
    }
}

When you open your file for reading or writing or whatever , you need to make sure it has been opened for sharing with other processes. There is Enum called FileShare for that! Try this:

  using (var stream = new FileStream(@"C:\data.csv",FileMode.Open, FileAccess.Read, 
            FileShare.ReadWrite)
            {
              using(var reader = new StreamReader(stream))
                {
                    List<string> listA = new List<string>();

                    while (!reader.EndOfStream)
                    {
                        var line = reader.ReadLine();
                        var values = line.Split(',');
                        string querynew = "INSERT INTO new_jobs"
                                  + "(job_reference,status)" 
                                  + "VALUES (?jobNo, ?strClientName)";

                            MySqlCommand cmd = connection.CreateCommand();
                    cmd.CommandText= querynew;
                            cmd.Parameters.Add("?jobNo", MySqlDbType.VarChar).Value = 
                                      (values[0]);
                            cmd.Parameters.Add("?strClientName", MySqlDbType.VarChar).Value =(values[1]);

                    cmd.ExecuteNonQuery(); 
                   56 filemove(); <-- error trigger line
                    }
                }
             }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM