【发布时间】: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