2009-12-16 3 views
33

기존 파일을 열고 선언 된 문자열과 일치하는 모든 문자열을 새 문자열로 바꾸고 저장 한 다음 닫는 것이 가장 좋습니다.파일 열기 및 C#의 문자열 바꾸기

제안 사항?

File.WriteAllText("Path", Regex.Replace(File.ReadAllText("Path"), "[Pattern]", "Replacement")); 
+0

을 : 당신이 만약 Visual Studio를 가지고 있다면, 솔루션에 폴더를 포함하고 검색을 사용하여 Visual Studio의 기능을 바꿀 수 있습니다. 행운의 – StackOrder

답변

74

한 줄에서 수행 할 수 있습니다 다음과 같은 ...

private static void ReplaceTextInFile(string originalFile, string outputFile, string searchTerm, string replaceTerm) 
{ 
    string tempLineValue; 
    using (FileStream inputStream = File.OpenRead(originalFile)) 
    { 
     using (StreamReader inputReader = new StreamReader(inputStream)) 
     { 
      using (StreamWriter outputWriter = File.AppendText(outputFile)) 
      { 
       while(null != (tempLineValue = inputReader.ReadLine())) 
       { 
        outputWriter.WriteLine(tempLineValue.Replace(searchTerm,replaceTerm)); 
       } 
      } 
     } 
    } 
} 

그런 다음 당신은 원본 파일을 제거하고 원래 이름으로 새 이름을 변경해야 할 것이다, 그러나 그것은 사소한 - 일부 바을 추가로 메소드에 오류가 있는지 확인하십시오.

물론 대체 텍스트가 두 줄 이상에 걸쳐있을 수 있다면 더 많은 작업을해야하지만 알아두면됩니다. :)

질문의 요구 사항을 충족
+5

이것은 전체 파일을 메모리에로드합니다. – Banshee

+1

설정 파일을 변경하는 데 아주 좋은 oneliner입니다. – Gorgsenegger

9
using System; 
using System.IO; 
using System.Text.RegularExpressions; 

public static void ReplaceInFile(
         string filePath, string searchText, string replaceText) 
{ 

    var content = string.Empty; 
    using (StreamReader reader = new StreamReader(filePath)) 
    { 
     content = reader.ReadToEnd(); 
     reader.Close(); 
    } 

    content = Regex.Replace(content, searchText, replaceText); 

    using (StreamWriter writer = new StreamWriter(filePath)) 
    { 
     writer.Write(content); 
     writer.Close(); 
    } 
} 
+2

+1, streamreader/writer 주위에'usings'을 추가하는 것이 좋습니다. 이것은 afaik가 가장 좋습니다. –

+0

FileReadAllText 및 StreamWriter로 StreamReader를 File.WriteAllText로 바꿀 수 있습니다. 조금 적은 코드 ... 또한 무엇을 대체 할 것인지에 따라 Regex.Escape searchText 또는 string.Replace를 사용해야 할 수도 있습니다. –

+1

메모리로 읽지 않고 파일을 한 줄씩 처리합니다. 파일을 대체하려면 새 파일에 기록한 다음 이전 파일 이름으로 복사하십시오. – CSharpAtl

25

당신이 이 대형 파일을 읽고, 및 교체에 대한 문자열이 여러 행으로 분리 표시되지 않을 수도 있습니다, 내가 뭔가를 건의 할 것입니다 :

+0

나는 중첩 사용에 쌓아두기에 찬성하지만 실제로는 그저 기본 설정이라고 생각합니다. 두 개 이상의 중첩이 나를 조금 어지럽게 만들었습니다.) –

+0

이진 코드를 지원하기 위해이 코드를 어떻게 수정할 수 있는지 알고 싶습니다. – Tomas

+0

거대한 파일은 무엇입니까? https://web.archive.org/web/20140316075223/http://towardsnext.wordpress.com/2009/02/02/replace-data-in-file-c/ – Kiquenet

9

약간의 정규식을 필요로하지 않는 제안 된 답변에 대한 개선 및 : 만 팁 등이 의견을 고려

File.WriteAllText("Path", File.ReadAllText("Path").Replace("SearchString", "Replacement")); 
0
public partial class ReadAndChange : System.Web.UI.Page 
{ 
    ArrayList FolderList = new ArrayList(); 
    ArrayList FolderListSearch = new ArrayList(); 
    ArrayList FileList = new ArrayList(); 
    protected void Page_Load(object sender, EventArgs e) 
    { 
     AllFolderList("D:\\BinodBackup\\Nilesh\\14.5.2013\\Source"); 
     foreach (string Path in FolderList) 
     { 
      AllFileList(Path); 
     } 
     foreach (string Path in FileList) 
     { 
      ReplaceFile(Path, Path.Replace("Source", "EditedCode")); 
     } 

     //string SourcePath = "D:\\BinodBackup\\Nilesh\\14.5.2013\\Onesource\\Onesource\\UserManagement\\UserControls\\AddUserDetails.ascx.cs"; 
     //string ReplacePath = "D:\\AddUserDetails.ascx.cs"; 
     //ReplaceFile(SourcePath, ReplacePath); 
    } 

    private static void ReplaceFile(string SourcePath, string ReplacePath) 
    { 
     int counter = 1; 
     string line; 

     // Read the file and display it line by line. 
     System.IO.StreamReader file = new System.IO.StreamReader(SourcePath); 
     while ((line = file.ReadLine()) != null) 
     { 
      if (!(line.Contains("//"))) 
      { 
       if (line.Contains(".LogException(")) 
       { 
        //Console.WriteLine(counter.ToString() + ": " + line); 
        string[] arr = line.Split(','); 
        string stringToReplace = arr[0].Replace("LogException", "Publish") + " , " + arr[2].Trim() + " , " + arr[3].Replace(");", "").Trim() + " , " + arr[1].Trim() + ");"; 
        //File.WriteAllText(currentPath, Regex.Replace(File.ReadAllText(currentPath), line, line + " Added")); 
        File.WriteAllText(ReplacePath, File.ReadAllText(ReplacePath).Replace(line, stringToReplace)); 
        //ReplaceInFile(currentPath, line, stringToReplace); 
       } 
      } 

      counter++; 
     } 

     file.Close(); 
    } 
    private void AllFileList(string FolderPath) 
    { 
     DirectoryInfo dir = new DirectoryInfo(FolderPath); 
     DirectoryInfo[] subdir = dir.GetDirectories(); 
     if (subdir.Length > 0) 
     { 

      foreach (DirectoryInfo dr in subdir) 
      { 
       FileInfo[] files1 = dr.GetFiles(); 
       foreach (FileInfo file in files1) 
       { 
        if(file.Name.EndsWith(".cs")) 
        CheckAndAdd((file.DirectoryName + "\\" + file.Name), FileList); 
       } 

      } 
     } 
    } 

    private void AllFolderList(string FolderPath) 
    { 
     string CurFolderPatgh = FolderPath; 
     Again: 
     AddToArrayList(CurFolderPatgh); 
     DirectoryInfo dir = new DirectoryInfo(CurFolderPatgh); 
     DirectoryInfo[] subdir = dir.GetDirectories(); 

     if (subdir.Length > 0) 
     { 
      foreach (DirectoryInfo dr in subdir) 
      { 
       AddToArrayList(((System.IO.FileSystemInfo)(dir)).FullName + "\\" + dr.Name); 
      } 
     } 
     if (FolderListSearch.Count > 0) 
     { 
      foreach (string dr in FolderListSearch) 
      { 
       CurFolderPatgh = dr; 
       FolderListSearch.Remove(dr); 
       goto Again; 
      } 
     } 
    } 

    private void AddToArrayList(string FolderPath) 
    { 
     if (!(FolderList.Contains(FolderPath))) 
     { 
      CheckAndAdd(FolderPath, FolderList); 
      CheckAndAdd(FolderPath, FolderListSearch); 
     } 
    } 

    private void CheckAndAdd(string FolderPath,ArrayList ar) 
    { 
     if (!(ar.Contains(FolderPath))) 
     { 
      ar.Add(FolderPath); 
     } 
    } 

    public static void ReplaceInFile(
         string filePath, string searchText, string replaceText) 
    { 

     var content = string.Empty; 
     using (StreamReader reader = new StreamReader(filePath)) 
     { 
      content = reader.ReadToEnd(); 
      reader.Close(); 
     } 

     content = content.Replace(searchText, replaceText); 

     using (StreamWriter writer = new StreamWriter(filePath)) 
     { 
      writer.Write(content); 
      writer.Close(); 
     } 
    } 
} 
0
using System; 
using System.Collections.Generic; 
using System.Globalization; 
using System.IO; 
using System.Linq; 

namespace DevExpressFileEditing 
{ 
    class Program 
    { 
     static List<FileInfo> _files; 
     private static Dictionary<string, string> _replaceList; 

     static void Main() 
     { 
      _files = new List<FileInfo>(); 
      _replaceList = new Dictionary<string, string>(); 

      Console.WriteLine("Dark directory searching"); 
      SearchFilesInDirectories(new DirectoryInfo(@"C:\Sourcebank\Dark")); 

      Console.WriteLine("Light directory searching"); 
      SearchFilesInDirectories(new DirectoryInfo(@"C:\Sourcebank\Light")); 

      Console.WriteLine("{0} files found", _files.Count.ToString(CultureInfo.InvariantCulture)); 

      Console.WriteLine("Replace dictinary creating"); 
      CreateReplaceList(); 
      Console.WriteLine("{0} item added", _replaceList.Count.ToString(CultureInfo.InvariantCulture)); 

      Console.Write("Replacement doing"); 
      for (int i = 0; i < _files.Count; i++) 
      { 
       var fileInfo = _files[i]; 
       Console.CursorLeft = 0; 
       Console.Write("{0} of {1}", i.ToString(CultureInfo.InvariantCulture), _files.Count.ToString(CultureInfo.InvariantCulture)); 
       ReplaceInFile(fileInfo.FullName); 
      } 
      Console.CursorLeft = 0; 
      Console.Write("Replacement done"); 
     } 

     private static void SearchFilesInDirectories(DirectoryInfo dir) 
     { 
      if (!dir.Exists) return; 

      foreach (DirectoryInfo subDirInfo in dir.GetDirectories()) 
       SearchFilesInDirectories(subDirInfo); 

      foreach (var fileInfo in dir.GetFiles()) 
       _files.Add(fileInfo); 
     } 

     private static void CreateReplaceList() 
     { 
      _replaceList.Add("Color=\"#FFF78A09\"", "Color=\"{DynamicResource AccentColor}\""); 
      _replaceList.Add("Color=\"{StaticResource ColorHot}\"", "Color=\"{DynamicResource AccentColor}\""); 
      _replaceList.Add("Color=\"#FFCC0000\"", "Color=\"{DynamicResource AccentColor}\""); 
      _replaceList.Add("To=\"#FFCC0000\"", "To=\"{DynamicResource AccentColor}\""); 
      _replaceList.Add("To=\"#FFF78A09\"", "To=\"{DynamicResource AccentColor}\""); 
      _replaceList.Add("Background=\"#FFF78A09\"", "Background=\"{DynamicResource Accent}\""); 
      _replaceList.Add("Foreground=\"#FFF78A09\"", "Foreground=\"{DynamicResource Accent}\""); 
      _replaceList.Add("BorderBrush=\"#FFF78A09\"", "BorderBrush=\"{DynamicResource Accent}\""); 
      _replaceList.Add("Value=\"#FFF78A09\"", "Value=\"{DynamicResource Accent}\""); 
      _replaceList.Add("Fill=\"#FFF78A09\"", "Fill=\"{DynamicResource Accent}\""); 
     } 

     public static void ReplaceInFile(string filePath) 
     { 
      string content; 
      using (var reader = new StreamReader(filePath)) 
      { 
       content = reader.ReadToEnd(); 
       reader.Close(); 
      } 

      content = _replaceList.Aggregate(content, (current, item) => current.Replace(item.Key, item.Value)); 

      using (var writer = new StreamWriter(filePath)) 
      { 
       writer.Write(content); 
       writer.Close(); 
      } 
     } 
    } 
} 
+0

Aggregate()를 사용하는 방법을 보여줍니다. 좋은 관행 인 +1을 사용하면서 텍스트를 대체하십시오. – shipr