2016-04-07 11 views
0

我想,如果它包含特定字符串移動文件,代碼如下移動在C#中的文本文件,如果它包含一個值

foreach (FileInfo file in files) 
     { 
      //reads the file contents 

       string MessageContents = File.ReadAllText(file.FullName); 
       //checks if the textwords are present in the file 
       foreach (string Keyword in textwords) 
       { 
        //if they are file is moved to quarantine messages 
        if (MessageContents.Contains(Keyword)) 
        { 
         try 
         { 
          File.Move(file.FullName, File_quarantine); 
         } 
         catch (IOException cannot_Move_File) 
         { 
          MessageBox.Show("The process has failed: {0}", cannot_Move_File.ToString()); 
         } 
         break; 
        } 
         //else it is moved To valid messages 
        else 
        { 
         try 
         { 
          File.Move(file.FullName, File_Valid); 
         } 
         catch (IOException cannot_Move_File) 
         { 
          MessageBox.Show("The process has failed: {0}", cannot_Move_File.ToString()); 
         } 
         break; 
        } 
       } 
      } 
     } 

但過程總是失敗,錯誤A first chance exception of type 'System.IO.IOException' occurred in mscorlib.dll

我不確定爲什麼發生這種情況,任何幫助將不勝感激。

+0

你仍然對文件上的鎖,因爲你開了一個流給它。移動文件移出文件讀數的邏輯。看到我的答案。 – Kolky

回答

0

您仍然對該文件有鎖定,因爲您打開了一個流。移動文件移出文件讀數的邏輯。

這應該會產生所需的結果;

foreach (FileInfo file in files) 
{ 
    String messageContents = File.ReadAllText(file.FullName); 
    bool toQuarantine = textwords.Any(keyWord => messageContents.Contains(keyWord)); 

    try 
    { 
     File.Move(file.FullName, toQuarantine ? File_quarantine : File_Valid); 
    } 
    catch (IOException cannot_Move_File) 
    { 
     MessageBox.Show("The process has failed: {0}", cannot_Move_File.ToString()); 
    } 
} 
+0

執行時仍然會出現同樣的錯誤 – bdg

+0

異常的消息是什麼? (你以前沒有指定) – Kolky

+0

我得到的錯誤是'System.IO.IOException:無法創建文件,當該文件已經存在.'但是該文件不存在於目標文件夾我試圖將其移動到 – bdg

0

基本上你已經鎖定了文件。閱讀時無法移動它。

如果文件比較小,你可以使用這樣的技術:

String content = File.ReadAllText(filename); 

// at this point, the file is not locked, unlike the 
// way it is in your question. you are free to move it 

foreach (String keyword in keywords) { 
    if (content.Contains(keyword)) { 
     // Move file 
     break; 
    } 
} 
+0

將嘗試和捕捉方法我已經使用工作,你指定'/ /移動文件'我編輯了問題,以反映你的意見,但我仍然得到相同的錯誤信息 – bdg

相關問題