У меня есть текстовый файл, который мне нужно обновить в соответствии с матча регулярного выражения, но как только моя программа пытается записать строку в текстовый файл, он дает следующую ошибку ..IOException при записи в текстовый файл в C#
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);
Где я иду не так?