简体   繁体   English

如何查找和替换文件中的文本

[英]How to find and replace text in a file

My code so far到目前为止我的代码

StreamReader reading = File.OpenText("test.txt");
string str;
while ((str = reading.ReadLine())!=null)
{
      if (str.Contains("some text"))
      {
          StreamWriter write = new StreamWriter("test.txt");
      }
}

I know how to find the text, but I have no idea on how to replace the text in the file with my own.我知道如何找到文本,但我不知道如何用我自己的文本替换文件中的文本。

Read all file content.读取所有文件内容。 Make a replacement with String.Replace .使用String.Replace进行替换。 Write content back to file.将内容写回文件。

string text = File.ReadAllText("test.txt");
text = text.Replace("some text", "new value");
File.WriteAllText("test.txt", text);

You're going to have a hard time writing to the same file you're reading from.您将很难写入正在读取的同一个文件。 One quick way is to simply do this:一种快速的方法是简单地这样做:

File.WriteAllText("test.txt", File.ReadAllText("test.txt").Replace("some text","some other text"));

You can lay that out better with你可以用

string str = File.ReadAllText("test.txt");
str = str.Replace("some text","some other text");
File.WriteAllText("test.txt", str);

You need to write all the lines you read into the output file, even if you don't change them.您需要将读取的所有行写入输出文件,即使您不更改它们。

Something like:就像是:

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);
  }
}

If you want to perform this operation in place then the easiest way is to use a temporary output file and at the end replace the input file with the output.如果您想就地执行此操作,那么最简单的方法是使用临时输出文件,最后用输出替换输入文件。

File.Delete("input.txt");
File.Move("output.txt", "input.txt");

(Trying to perform update operations in the middle of text file is rather hard to get right because always having the replacement the same length is hard given most encodings are variable width.) (尝试在文本文件的中间执行更新操作是相当困难的,因为鉴于大多数编码都是可变宽度,因此总是很难替换相同的长度。)

EDIT: Rather than two file operations to replace the original file, better to use File.Replace("input.txt", "output.txt", null) .编辑:与其使用两个文件操作来替换原始文件,不如使用File.Replace("input.txt", "output.txt", null) (See MSDN .) (请参阅MSDN 。)

It is likely you will have to pull the text file into memory and then do the replacements.您可能必须将文本文件拉入内存,然后进行替换。 You will then have to overwrite the file using the method you clearly know about.然后,您必须使用您清楚了解的方法覆盖该文件。 So you would first:所以你首先要:

// Read lines from source file.
string[] arr = File.ReadAllLines(file);

YOu can then loop through and replace the text in the array.然后,您可以循环遍历并替换数组中的文本。

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);
}

this method gives you some control on the manipulations you can do.此方法可让您对可以执行的操作进行一些控制。 Or, you can merely do the replace in one line或者,您可以仅在一行中进行替换

File.WriteAllText("test.txt", text.Replace("match", "new value"));

I hope this helps.我希望这有帮助。

This is how I did it with a large (50 GB) file:这是我用一个大(50 GB)文件做的:

I tried 2 different ways: the first, reading the file into memory and using Regex Replace or String Replace.我尝试了两种不同的方法:第一种,将文件读入内存并使用 Regex Replace 或 String Replace。 Then I appended the entire string to a temporary file.然后我将整个字符串附加到一个临时文件中。

The first method works well for a few Regex replacements, but Regex.Replace or String.Replace could cause out of memory error if you do many replaces in a large file.第一种方法适用于一些 Regex 替换,但如果您在一个大文件中进行多次替换,Regex.Replace 或 String.Replace 可能会导致内存不足错误。

The second is by reading the temp file line by line and manually building each line using StringBuilder and appending each processed line to the result file.第二种是通过逐行读取临时文件并使用 StringBuilder 手动构建每一行并将每个处理过的行附加到结果文件中。 This method was pretty fast.这个方法相当快。

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();
    }

i tend to use simple forward code as much as i can ,below code worked fine with me我倾向于尽可能多地使用简单的前向代码,下面的代码对我来说很好用

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();
}

This code Worked for me这段代码对我有用

- //-------------------------------------------------------------------
                           // 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM