2014-01-23 5 views
0

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

Где я иду не так?

ответ

0

Использование File.Create(textfilename).Close();

В сообщении об ошибке предлагает

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. 
Смежные вопросы