文件正在被另一个进程使用,除非它不是

时间:2013-07-01 09:58:30

标签: c# xml visual-studio-2010 linq parsing

我目前正在开发一个实用程序来解析多个xml文件,并将结果写入csv文件。在第二行(代码)上我收到错误:

The process cannot access the file 'W:\SRC\hDefML\myExcelFile.csv' because it is being used by another process.'.

有人可以帮助我,因为我不知道什么是错的,该文件没有被其他任何东西使用,这让我发疯了?

这是我的代码。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;
using System.IO;

namespace GenNameUtility
{
    class NameGenerator
    {
        static void Main(string[] args)

        {
            var files = from file in       Directory.GetFiles("W:\\SRC\\hDefMl\\1.0\\Instrument_Files") orderby file 
        ascending select file;

        StringBuilder sb_report = new StringBuilder();

        string delimiter = ",";

        sb_report.AppendLine(string.Join(delimiter, "Module", "Generator(s)"));

        foreach (var file in files)
        {
            string filename = Path.GetFileNameWithoutExtension(file);

            Console.Write("The HDefML file for {0} contains these EEPROM Generators:", filename);

            XDocument hdefml = XDocument.Load(file);

                var GeneratorNames = from b in hdefml.Descendants("Generators") select new
        {
           name = (string)b.Element("GeneratorName") 

        }.ToString();

        StringBuilder sb = new StringBuilder();
        foreach (var item in GeneratorNames)
        {
            Console.Write("  GeneratorName is: {0}", GeneratorNames);
            sb_report.AppendLine(string.Join(delimiter, filename, GeneratorNames));

        var hdef = File.Create(@"W:\SRC\hDefML\myExcelFile.csv").ToString();
        File.WriteAllText(hdef, sb.ToString());
        }          
     }
        Console.ReadLine();
}
}

}

3 个答案:

答案 0 :(得分:5)

您需要在写入文件后关闭该文件。请参阅using

最好在循环之前打开文件然后关闭它。

答案 1 :(得分:2)

该文件正由另一个进程使用......但该进程实际上是您的。

File.Create返回FileStream。你正在打开文件..写信给它..但没有关闭它。当新的迭代出现时......文件仍然打开。

您可以尝试这样的事情:

using (var file = File.Create(@"W:\SRC\hDefML\myExcelFile.csv")) {
    // write content here using file
} // this closes the file automatically.

正如所建议的那样,我会将上面的内容包装在循环之外,因此您不会经常打开和关闭文件。

答案 2 :(得分:0)

File.WriteAllText会为您创建一个文件,因此无需事先使用File.Create

File.WriteAllText(@"W:\SRC\hDefML\myExcelFile.csv", sb.ToString());

您的File.Create流似乎正在锁定文件,这就是File.WriteAllText抛出错误的原因。

如果您需要使用File.Create,可以使用StreamWriter将其写出来。

using(var fs = File.Create(@"W:\SRC\hDefML\myExcelFile.csv"))
using (StreamWriter sw = new StreamWriter(fs))
{
    sw.Write(sb.ToString());                  
}

作为旁注,上述using格式与执行

相同
using(var fs = File.Create(@"W:\SRC\hDefML\myExcelFile.csv"))
{
   using (StreamWriter sw = new StreamWriter(fs))
   {
      sw.Write(sb.ToString());                  
   }
}

所以你可以使用你觉得更具可读性的那些。