Подтвердить что ты не робот

Как найти и заменить текст в файле с помощью С#

Мой код пока

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

Я знаю, как найти текст, но я понятия не имею, как заменить текст в файле моим собственным.

4b9b3361

Ответ 1

Читать все содержимое файла. Сделайте замену с помощью String.Replace. Запишите содержимое обратно в файл.

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

Ответ 2

У вас будет трудное время писать в тот же файл, который вы читаете. Один быстрый способ - просто сделать это:

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

Ответ 3

Вам нужно записать все строки, которые вы читаете в выходной файл, даже если вы не измените их.

Что-то вроде:

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

(Попытка выполнить операции обновления в середине текстового файла довольно сложно, потому что всегда иметь замену той же длины трудно, поскольку большинство кодировок являются переменной шириной.)

EDIT: Вместо двух файлов для замены исходного файла лучше использовать File.Replace("input.txt", "output.txt", null). (См. MSDN.)

Ответ 4

Вероятно, вам придется вытащить текстовый файл в память, а затем выполнить замены. Затем вам придется перезаписать файл, используя метод, о котором вы точно знаете. Итак, сначала вы:

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

Надеюсь, это поможет.

Ответ 5

Вот как я это сделал с большим (50 ГБ) файлом:

Я пробовал 2 разных способа: первый - чтение файла в память и использование 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();
    }

Ответ 6

Этот код работал для меня

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

Ответ 7

Я стараюсь использовать простой код пересылки, насколько это возможно, нижеприведенный код отлично работает со мной

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