【问题标题】:The file cannot be accessed because it is being used by another process c#该文件无法访问,因为它正被另一个进程使用 c#
【发布时间】:2018-10-05 12:19:24
【问题描述】:

我编写了一个 Windows 服务来将 CSV 文件从原始位置复制到新位置。

之后,新位置的 CSV 已经被读写到 MySQL。

由于文件移动服务触发错误,上述任务曾经作为 2 个单独的服务运行:

{"进程无法访问文件'C:\data.csv',因为它是 正在被另一个进程使用。"}

因此,我决定将 2 个服务合并为 1 个,但我仍然遇到了同样的问题。

我的代码如下。

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

//文件移动函数

 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

我没有在方法中包含其余代码。

void timer1_Tick(object sender, ElapsedEventArgs e)
        {

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

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

错误在 Insert() 方法内的第 56 行触发。

【问题讨论】:

    标签: c# windows-services


    【解决方案1】:

    先关闭连接,再调用。

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

    【讨论】:

      【解决方案2】:

      尚不清楚 filemove() 方法中发生了什么来触发错误,它可能在未包含的部分中更进一步。话虽如此,您可以尝试在 StreamReader 的 using 块之后将调用移动到 filemove() (如下所示)。在 using 块中,StreamReader 仍然打开文件,并且可能会限制 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();
          }
      }
      

      【讨论】:

        【解决方案3】:

        当您打开文件进行读取或写入或其他操作时,您需要确保它已打开以与其他进程共享。为此,有一个名为 FileShare 的枚举! 试试这个:

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

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2023-01-17
          • 2013-06-28
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2010-12-10
          相关资源
          最近更新 更多