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

时间:2021-06-07 16:51:16

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.

我知道如何查找文本,但是我不知道如何用我自己的文本替换文件中的文本。

5 个解决方案

#1


219  

Read all file content. Make a replacement with 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);

#2


28  

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

#3


20  

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). (See MSDN.)

编辑:与其使用两个文件操作替换原始文件,不如使用file . replace(“输入”)。txt”、“输出。txt”,null)。(见MSDN。)

#4


7  

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.

我希望这可以帮助。

#5


0  

I accomplished this by using 2 different ways, the first: reading the file into memory and using Regex Replace or String Replace. Then I append the entire string to a temporary file.

我使用了两种不同的方法来实现这一点,第一种方法是:将文件读入内存并使用Regex替换或字符串替换。然后我将整个字符串附加到一个临时文件。

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.

第二种方法是通过逐行读取temp文件,并使用StringBuilder手动构建每个行,并将每个处理后的行追加到结果文件中。

The first method works well for general Regex replacements, but it hogs memory if you try do do Regex.Matches in a large file.

第一个方法对于常规的Regex替换非常有效,但是如果您尝试使用Regex,它会占用内存。匹配一个大文件。

    static void ProcessLargeFile()
    {

        if (File.Exists(outputDefsFileName)) File.Delete(outputDefsFileName);
        if (File.Exists(defTempProc1FileName)) File.Delete(defTempProc1FileName);
        if (File.Exists(defTempProc2FileName)) File.Delete(defTempProc2FileName);

        string text = File.ReadAllText(inputDefsFileName, Encoding.UTF8);

        // PROC 1 This opens entire file in memory and uses Replace and Regex Replace

        text = text.Replace("</text>", "");

        text = Regex.Replace(text, @"\<ref.*?\</ref\>", "");

        File.WriteAllText(defTempProc1FileName, text);

        // PROC 2 This reads file line by line and uses String.IndexOf and String.Substring and StringBuilder to build the new lines 


        using (var fileStream = File.OpenRead(defTempProc1FileName))
        using (var streamReader = new StreamReader(fileStream, Encoding.UTF8))
        {
            string line, newdef;

            while ((line = streamReader.ReadLine()) != null)
            {

                String[] arr = line.Split('\t');

                string def = arr[2];

                newdef = Util.ProcessDoubleBrackets(def);

                File.AppendAllText(defTempProc2FileName, newdef  + Environment.NewLine);
            }
        }
    }

    public static string ProcessDoubleBrackets(string def)
    {
        if (def.IndexOf("[[") < 0)
            return def;

        StringBuilder sb = new StringBuilder();
        ... Some processing

        sb.Append(def.Substring(pos, i - pos));

        ... Some processing
        return sb.ToString();
    }

#1


219  

Read all file content. Make a replacement with 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);

#2


28  

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

#3


20  

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). (See MSDN.)

编辑:与其使用两个文件操作替换原始文件,不如使用file . replace(“输入”)。txt”、“输出。txt”,null)。(见MSDN。)

#4


7  

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.

我希望这可以帮助。

#5


0  

I accomplished this by using 2 different ways, the first: reading the file into memory and using Regex Replace or String Replace. Then I append the entire string to a temporary file.

我使用了两种不同的方法来实现这一点,第一种方法是:将文件读入内存并使用Regex替换或字符串替换。然后我将整个字符串附加到一个临时文件。

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.

第二种方法是通过逐行读取temp文件,并使用StringBuilder手动构建每个行,并将每个处理后的行追加到结果文件中。

The first method works well for general Regex replacements, but it hogs memory if you try do do Regex.Matches in a large file.

第一个方法对于常规的Regex替换非常有效,但是如果您尝试使用Regex,它会占用内存。匹配一个大文件。

    static void ProcessLargeFile()
    {

        if (File.Exists(outputDefsFileName)) File.Delete(outputDefsFileName);
        if (File.Exists(defTempProc1FileName)) File.Delete(defTempProc1FileName);
        if (File.Exists(defTempProc2FileName)) File.Delete(defTempProc2FileName);

        string text = File.ReadAllText(inputDefsFileName, Encoding.UTF8);

        // PROC 1 This opens entire file in memory and uses Replace and Regex Replace

        text = text.Replace("</text>", "");

        text = Regex.Replace(text, @"\<ref.*?\</ref\>", "");

        File.WriteAllText(defTempProc1FileName, text);

        // PROC 2 This reads file line by line and uses String.IndexOf and String.Substring and StringBuilder to build the new lines 


        using (var fileStream = File.OpenRead(defTempProc1FileName))
        using (var streamReader = new StreamReader(fileStream, Encoding.UTF8))
        {
            string line, newdef;

            while ((line = streamReader.ReadLine()) != null)
            {

                String[] arr = line.Split('\t');

                string def = arr[2];

                newdef = Util.ProcessDoubleBrackets(def);

                File.AppendAllText(defTempProc2FileName, newdef  + Environment.NewLine);
            }
        }
    }

    public static string ProcessDoubleBrackets(string def)
    {
        if (def.IndexOf("[[") < 0)
            return def;

        StringBuilder sb = new StringBuilder();
        ... Some processing

        sb.Append(def.Substring(pos, i - pos));

        ... Some processing
        return sb.ToString();
    }