【问题标题】:IoException while writing in text file in c#在 C# 中写入文本文件时出现 IoException
【发布时间】:2014-01-23 09:23:19
【问题描述】:

我有需要根据正则表达式匹配更新的文本文件,但是一旦我的程序尝试将一行写入文本文件,它就会给出以下错误..

The process cannot access the file 'D:\Archieve\20140123.text' because it is being used by another process.

这是我的 C# 代码..

static void Main(string[] args)
    {
        string textfilename="";
        string strDateTime = DateTime.Now.ToString("yyyyMMdd");
        string strformatedatetime = DateTime.Now.ToString("yyyy/MM/dd");
        if (strDateTime != "") {

            string loc = "D:\\Archieve\\";
            string date=strDateTime;
            string text=".text";
            textfilename = loc + date + text;
            File.Create(textfilename);                
        }
        string pattern = "^" + strformatedatetime + ".*";
        string FileToCopy = "D:\\ipdata.txt";
        string NewCopy =textfilename;
        StringBuilder sb = new StringBuilder("");
        List<string> newLines = new List<string>();

        if (System.IO.File.Exists(FileToCopy) == true)
        {
            string[] lines = File.ReadAllLines(FileToCopy);
            foreach (string line in lines)
            {
                if (Regex.IsMatch(line, pattern))
                {
                    sb.Append(line + System.Environment.NewLine);

                    TextWriter tsw = new StreamWriter(textfilename,true);
                    //Writing text to the file.
                    tsw.WriteLine(sb);
                    //Close the file.
                    tsw.Close();    
                }
            }
        }
    }

我在这行代码中遇到了超出定义的错误...

TextWriter tsw = new StreamWriter(textfilename,true);

我哪里错了?

【问题讨论】:

    标签: c# regex text-files file-handling


    【解决方案1】:

    您不需要单独的指令来创建文件。 StreamWriter 会处理它:这是您使用的构造函数的描述

    > Initializes a new instance of the StreamWriter class for the specified
    > file by using the default encoding and buffer size. If the file
    > exists, it can be either overwritten or appended to. If the file does
    > not exist, this constructor creates a new file.
    

    【讨论】:

      【解决方案2】:

      使用File.Create(textfilename).Close();

      正如错误信息提示的那样

      【讨论】:

        猜你喜欢
        • 2017-12-07
        • 1970-01-01
        • 2010-11-22
        • 2011-09-10
        • 1970-01-01
        • 1970-01-01
        • 2011-09-26
        • 2012-07-13
        • 1970-01-01
        相关资源
        最近更新 更多