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

1 c# xml linq parsing visual-studio-2010

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

The process cannot access the file 'W:\SRC\hDefML\myExcelFile.csv' because it is being used by another process.'.
Run Code Online (Sandbox Code Playgroud)

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

这是我的代码.

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();
}
}
Run Code Online (Sandbox Code Playgroud)

}

Jef*_*Son 5

您需要在写入文件后关闭该文件.见using.

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