我有根据正则表达式匹配需要更新的文本文件但是一旦我的程序尝试将一行写入文本文件,它就会发出以下错误..
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);
我哪里错了?
答案 0 :(得分: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.
答案 1 :(得分:0)
使用File.Create(textfilename).Close();
如错误消息所示