【问题标题】:File cannot be accessed because it is being used by another program无法访问文件,因为它正被另一个程序使用
【发布时间】:2012-07-31 12:03:06
【问题描述】:

我正在尝试删除行尾的空格,然后该行将写入另一个文件。

但是当程序到达FileWriter 时,它会给我以下错误

进程无法访问,因为它正被另一个进程使用。

代码如下。

private void FrmCounter_Load(object sender, EventArgs e)
{
        string[] filePaths = Directory.GetFiles(@"D:\abc", "*.txt", SearchOption.AllDirectories);
        string activeDir = @"D:\dest";
        System.IO.StreamWriter fw;
        string result;

        foreach (string file in filePaths)
        {
            result = Path.GetFileName(file);
            System.IO.StreamReader f = new StreamReader(file);
            string newFileName = result;
            // Combine the new file name with the path
            string newPath = System.IO.Path.Combine(activeDir, newFileName);
            File.Create(newPath);

            fw = new StreamWriter(newPath);

            int counter = 0;
            int spaceAtEnd = 0;
            string line;

            // Read the file and display it line by line.
            while ((line = f.ReadLine()) != null)
            {
                if (line.EndsWith(" "))
                {
                    spaceAtEnd++;
                    line = line.Substring(0, line.Length - 1);
                }
                fw.WriteLine(line);
                fw.Flush(); 
                counter++;
            }

            MessageBox.Show("File Name : " + result);
            MessageBox.Show("Total Space at end : " + spaceAtEnd.ToString());
            f.Close();
            fw.Close();
        }
}

【问题讨论】:

  • 嗯,文件显然是被另一个程序打开的。如果它作为窗口打开,也许尝试关闭它?也许另一个程序已经像您尝试的那样打开了?
  • 猜测一下,因为您将 activeDir 和 filePaths 设置为同一个目录,所以您正试图写入您正在读取的同一个文件。
  • 好吧,我也尝试了另一个目录..但同样的错误

标签: c# file-io


【解决方案1】:

File.Create 本身返回一个流。

使用该流写入文件。您收到此错误的原因是 File.Create 返回的 Stream 已打开,您正尝试再次打开该文件以进行写入。

要么关闭File.Create 返回的流,要么更好地使用该流进行文件写入或使用

Stream newFile = File.Create(newPath);
fw = new StreamWriter(newFile);

【讨论】:

    【解决方案2】:

    即使您解决了最初的问题,如果您想将所有内容写入原始位置的新文件,您可以尝试将所有数据读入数组并关闭原始StreamReader。性能说明:但如果您的文件足够大,则此选项不会是最佳性能。

    并且您不需要File.Create,因为StreamWriter 将创建一个文件,如果它不存在,或者默认覆盖它,或者如果您将append 参数指定为false

    result = Path.GetFileName(file);
    String[] f = File.ReadAllLines(file);  // major change here... 
                                           //  now f is an array containing all lines 
                                           //  instead of a stream reader
    
    using(var fw = new StreamWriter(result, false))
    {
        int counter = f.Length; // you aren't using counter anywhere, so I don't know if 
                                //  it is needed, but now you can just access the `Length`  
                                //  property of the array and get the length without a 
                                //  counter
    
        int spaceAtEnd = 0;
    
        // Read the file and display it line by line.
        foreach (var item in f)
        {
            var line = item;
    
            if (line.EndsWith(" "))
            {
                spaceAtEnd++;
                line = line.Substring(0, line.Length - 1);
            }
            fw.WriteLine(line);
            fw.Flush(); 
        }
    }
    
    MessageBox.Show("File Name : " + result);
    MessageBox.Show("Total Space at end : " + spaceAtEnd.ToString());
    

    此外,您不会使用此方法从行尾删除多个空格。如果您需要这样做,请考虑将line = line.Substring(0, line.Length - 1); 替换为line = line.TrimEnd(' ');

    【讨论】:

      【解决方案3】:

      在您尝试写入文件之前,您必须关闭正在阅读的所有文件。

      【讨论】:

        【解决方案4】:

        using语句中写流,比如:

        using (System.IO.StreamReader f = new StreamReader(file))
        {
           //your code goes here
        }
        

        【讨论】:

          【解决方案5】:

          编辑:

          Zafar 是正确的,但是,也许这会澄清事实。

          因为 File.Create 返回一个流......那个流已经打开了你的目标文件。这会让事情变得更清楚:

          File.Create(newPath).Close();
          

          使用上面的行,它可以工作,但是,我建议正确地重写它。这仅用于说明目的。

          【讨论】:

          • 你是对的西蒙,但我编辑了目标路径,以为我得到了同样的错误
          猜你喜欢
          • 2018-03-27
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2013-03-15
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多