2009-12-16 17 views
33

में तारों को प्रतिस्थापित करें। मैं मौजूदा फ़ाइल खोलने का सबसे अच्छा तरीका जानने और एक नई स्ट्रिंग के साथ घोषित स्ट्रिंग से मेल खाने वाले सभी तारों को प्रतिस्थापित करने का प्रयास कर रहा हूं, इसे फिर से सहेजें।एक फ़ाइल खोलें और सी #

सुझाव?

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

केवल एक टिप के रूप में इस टिप्पणी पर विचार करें: यदि आप दृश्य स्टूडियो है, तो आप समाधान में फ़ोल्डर शामिल हैं और खोज का उपयोग करें और भाग्य – 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)); 
       } 
      } 
     } 
    } 
} 

तो फिर तुम मूल फ़ाइल निकाल सकते हैं और मूल नाम नया नाम बदलने के लिए होगा, लेकिन वह तुच्छ है - के रूप में कुछ बा जोड़ने है विधि में जांच त्रुटि एसआईसी।

बेशक, यदि आपका प्रतिस्थापन टेक्स्ट दो या दो से अधिक लाइनों में हो सकता है, तो आपको थोड़ा और काम करना होगा, लेकिन मैं इसे समझने के लिए आपको छोड़ दूंगा। :)

सुझाव दिया जवाब यह है कि Regex की आवश्यकता नहीं है पर
+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 के दृश्य स्टूडियो सर्वश्रेष्ठ की सुविधा की जगह ले सकता है, तो आप 'usings' StreamReader/लेखक, जो afaik सबसे अच्छा अभ्यास है चारों ओर जोड़ने के लिए चाहते हो सकता है। –

+0

आप FileRriteAllText के साथ FileReadAllText और StreamWriter के साथ StreamReader को प्रतिस्थापित कर सकते हैं। थोड़ा कम कोड ... इसके अलावा, आप जो बदल रहे हैं उसके आधार पर, आपको Regex.Escape खोज टेक्स्ट की आवश्यकता हो सकती है, या स्ट्रिंग का उपयोग करें। बदलें। –

+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

के सकल() का उपयोग करने के लिए कैसे दिखा लिए जबकि अभी भी अच्छा प्रथाओं का उपयोग कर, +1 टेक्स्ट को बदलें। – shipr

संबंधित मुद्दे