[英]How to find and replace text in a file
到目前為止我的代碼
StreamReader reading = File.OpenText("test.txt");
string str;
while ((str = reading.ReadLine())!=null)
{
if (str.Contains("some text"))
{
StreamWriter write = new StreamWriter("test.txt");
}
}
我知道如何找到文本,但我不知道如何用我自己的文本替換文件中的文本。
讀取所有文件內容。 使用String.Replace
進行替換。 將內容寫回文件。
string text = File.ReadAllText("test.txt");
text = text.Replace("some text", "new value");
File.WriteAllText("test.txt", text);
您將很難寫入正在讀取的同一個文件。 一種快速的方法是簡單地這樣做:
File.WriteAllText("test.txt", File.ReadAllText("test.txt").Replace("some text","some other text"));
你可以用
string str = File.ReadAllText("test.txt");
str = str.Replace("some text","some other text");
File.WriteAllText("test.txt", str);
您需要將讀取的所有行寫入輸出文件,即使您不更改它們。
就像是:
using (var input = File.OpenText("input.txt"))
using (var output = new StreamWriter("output.txt")) {
string line;
while (null != (line = input.ReadLine())) {
// optionally modify line.
output.WriteLine(line);
}
}
如果您想就地執行此操作,那么最簡單的方法是使用臨時輸出文件,最后用輸出替換輸入文件。
File.Delete("input.txt");
File.Move("output.txt", "input.txt");
(嘗試在文本文件的中間執行更新操作是相當困難的,因為鑒於大多數編碼都是可變寬度,因此總是很難替換相同的長度。)
編輯:與其使用兩個文件操作來替換原始文件,不如使用File.Replace("input.txt", "output.txt", null)
。 (請參閱MSDN 。)
您可能必須將文本文件拉入內存,然后進行替換。 然后,您必須使用您清楚了解的方法覆蓋該文件。 所以你首先要:
// Read lines from source file.
string[] arr = File.ReadAllLines(file);
然后,您可以循環遍歷並替換數組中的文本。
var writer = new StreamWriter(GetFileName(baseFolder, prefix, num));
for (int i = 0; i < arr.Length; i++)
{
string line = arr[i];
line.Replace("match", "new value");
writer.WriteLine(line);
}
此方法可讓您對可以執行的操作進行一些控制。 或者,您可以僅在一行中進行替換
File.WriteAllText("test.txt", text.Replace("match", "new value"));
我希望這有幫助。
這是我用一個大(50 GB)文件做的:
我嘗試了兩種不同的方法:第一種,將文件讀入內存並使用 Regex Replace 或 String Replace。 然后我將整個字符串附加到一個臨時文件中。
第一種方法適用於一些 Regex 替換,但如果您在一個大文件中進行多次替換,Regex.Replace 或 String.Replace 可能會導致內存不足錯誤。
第二種是通過逐行讀取臨時文件並使用 StringBuilder 手動構建每一行並將每個處理過的行附加到結果文件中。 這個方法相當快。
static void ProcessLargeFile()
{
if (File.Exists(outFileName)) File.Delete(outFileName);
string text = File.ReadAllText(inputFileName, Encoding.UTF8);
// EX 1 This opens entire file in memory and uses Replace and Regex Replace --> might cause out of memory error
text = text.Replace("</text>", "");
text = Regex.Replace(text, @"\<ref.*?\</ref\>", "");
File.WriteAllText(outFileName, text);
// EX 2 This reads file line by line
if (File.Exists(outFileName)) File.Delete(outFileName);
using (var sw = new StreamWriter(outFileName))
using (var fs = File.OpenRead(inFileName))
using (var sr = new StreamReader(fs, Encoding.UTF8)) //use UTF8 encoding or whatever encoding your file uses
{
string line, newLine;
while ((line = sr.ReadLine()) != null)
{
//note: call your own replace function or use String.Replace here
newLine = Util.ReplaceDoubleBrackets(line);
sw.WriteLine(newLine);
}
}
}
public static string ReplaceDoubleBrackets(string str)
{
//note: this replaces the first occurrence of a word delimited by [[ ]]
//replace [[ with your own delimiter
if (str.IndexOf("[[") < 0)
return str;
StringBuilder sb = new StringBuilder();
//this part gets the string to replace, put this in a loop if more than one occurrence per line.
int posStart = str.IndexOf("[[");
int posEnd = str.IndexOf("]]");
int length = posEnd - posStart;
// ... code to replace with newstr
sb.Append(newstr);
return sb.ToString();
}
我傾向於盡可能多地使用簡單的前向代碼,下面的代碼對我來說很好用
using System;
using System.IO;
using System.Text.RegularExpressions;
/// <summary>
/// Replaces text in a file.
/// </summary>
/// <param name="filePath">Path of the text file.</param>
/// <param name="searchText">Text to search for.</param>
/// <param name="replaceText">Text to replace the search text.</param>
static public void ReplaceInFile( string filePath, string searchText, string replaceText )
{
StreamReader reader = new StreamReader( filePath );
string content = reader.ReadToEnd();
reader.Close();
content = Regex.Replace( content, searchText, replaceText );
StreamWriter writer = new StreamWriter( filePath );
writer.Write( content );
writer.Close();
}
這段代碼對我有用
- //-------------------------------------------------------------------
// Create an instance of the Printer
IPrinter printer = new Printer();
//----------------------------------------------------------------------------
String path = @"" + file_browse_path.Text;
// using (StreamReader sr = File.OpenText(path))
using (StreamReader sr = new System.IO.StreamReader(path))
{
string fileLocMove="";
string newpath = Path.GetDirectoryName(path);
fileLocMove = newpath + "\\" + "new.prn";
string text = File.ReadAllText(path);
text= text.Replace("<REF>", reference_code.Text);
text= text.Replace("<ORANGE>", orange_name.Text);
text= text.Replace("<SIZE>", size_name.Text);
text= text.Replace("<INVOICE>", invoiceName.Text);
text= text.Replace("<BINQTY>", binQty.Text);
text = text.Replace("<DATED>", dateName.Text);
File.WriteAllText(fileLocMove, text);
// Print the file
printer.PrintRawFile("Godex G500", fileLocMove, "n");
// File.WriteAllText("C:\\Users\\Gunjan\\Desktop\\new.prn", s);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.