2012-08-23 51 views
2

我需要獲取包含字符串MySettings.xru的目錄及其子目錄中的所有* .config文件。替換包含某些文本但僅包含特定行的所有文件中的字符串

在所有找到的文件中,僅在包含字符串MySettings.xru的行上,我需要用db002替換文本db001。

因此,舉例來說,如果我有:

RandomSettings.xru someOtherWords Database=db001 blah, blah, blah... 
MySettings.xru Lalala Database=db001 blah, blah, blah... 
YourSettings.xru Hey yo Database=db001 blah, blah, blah... 

結果應該是:

RandomSettings.xru someOtherWords Database=db001 blah, blah, blah... 
MySettings.xru Lalala Database=db002 blah, blah, blah... 
YourSettings.xru Hey yo Database=db001 blah, blah, blah... 

謝謝!

更新:自己解決。

+2

查找文件(遞歸目錄搜索),分別處理文件,讀取每一行,檢查匹配,匹配的String.Replace,將行寫入臨時文件,關閉打開的文件,重命名(移動)臨時文件以覆蓋原始文件。 – musefan

+1

你到目前爲止嘗試過什麼?你的問題在哪裏?你不知道使用什麼整體方法?你不知道如何做文件訪問?你不知道如何修改文件?你不知道如何找到你需要改變的路線......這個問題目前涵蓋了很多地方,如果你提供了更多關於你需要幫助哪些位和哪些位需要幫助的想法與...最好用你試過的代碼。 :) – Chris

+0

請僅將此評論視爲提示:如果您有Visual Studio,則可以在解決方案中包含這些文件夾,並使用visual studio的搜索和替換功能。祝你好運 – StackOrder

回答

1

這裏是我的解決方案:

string[] filePaths = Directory.GetFiles(@"C:\test\", "*.config", SearchOption.AllDirectories); 

int counter = 0; 
string currentFile = string.Empty; 
string currentLine = string.Empty; 
string updatedLine = string.Empty; 

foreach (string file in filePaths) 
{ 
    currentFile = File.ReadAllText(file); 

    if (currentFile.Contains("MySettings.xru")) 
    { 
     counter++; 
     Debug.Print("Found in " + file); 

     using (StreamReader streamReader = new StreamReader(file)) 
     { 
      while (!streamReader.EndOfStream) 
      { 
       currentLine = streamReader.ReadLine(); 

       if (currentLine.Contains("MySettings.xru")) 
       { 
        updatedLine = currentLine.Replace("db001", "db002"); 

        break; 
       } 
      } 
     } 

     currentFile = currentFile.Replace(currentLine, updatedLine); 

     // If file is ReadOnly then remove that attribute. 
     FileAttributes attributes = File.GetAttributes(file); 
     if ((attributes & FileAttributes.ReadOnly) == FileAttributes.ReadOnly) 
      File.SetAttributes(file, attributes^FileAttributes.ReadOnly); 

     using (StreamWriter streamWriter = new StreamWriter(file)) 
     { 
      streamWriter.Write(currentFile); 
     } 
    } 
} 
0

在上面的回答;

串[]文件路徑= Directory.GetFiles(@ 「C:\測試\」,*的.config」,SearchOption.AllDirectories);

指定搜索模式和搜索選項沒有工作對我來說(對什麼都原因),但是根本提的搜索目錄也可以做的伎倆

的String []文件路徑= Directory.GetFiles(searchDirectory);

0

僅將此評論視爲提示:如果您有Visual Studio,則可以在解決方案中包含文件夾並使用Visual Studio的搜索和替換功能。祝您好運

相關問題