c# - 文件正在被另一个进程使用,但它不是

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

最佳答案

写入文件后需要关闭文件。请参阅使用

此外,最好在循环之前打开文件并在循环之后关闭它。

关于c# - 文件正在被另一个进程使用,但它不是,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17401695/

相关文章:

c# - 如何模拟 ReflectionTypeLoadException?

java - 如何使用xsl :variable in xsl:choose

xml - 如何 grep 我的 xml 文件并保存输出?

java - 如何检测XPath代表的是叶节点或者节点集?

c++ - 英特尔 TBB 集成问题 - Google 测试项目中的 VS2013 编译错误

c# - 如何访问数据集中的数据表

c# - 如何在 XAML 中访问父模板样式的元素?

c# - 使用带参数的数据表 sAjaxSource

visual-studio-2010 - 在 Visual Studio 2010 中使用 MS SQL Server 2005 Reporting Services

visual-studio-2010 - 如何使用 Coderush Express 重新排列类(class)成员