Cómo Encontrar Y Reemplazar Texto En Un Archivo Con C#


Mi código hasta ahora

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

Sé cómo encontrar el texto, pero no tengo idea de cómo reemplazar el texto en el archivo con el mío.

5 answers

Lee todo el contenido del archivo. Hacer un reemplazo con String.Replace. Volver a escribir contenido en el archivo.

string text = File.ReadAllText("test.txt");
text = text.Replace("some text", "new value");
File.WriteAllText("test.txt", text);
 235
Author: Sergey Berezovskiy,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-11-22 09:38:00

Vas a tener dificultades para escribir en el mismo archivo desde el que estás leyendo. Una forma rápida es simplemente hacer esto:

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

Puedes explicarlo mejor con

string str = File.ReadAllText("test.txt");
str = str.Replace("some text","some other text");
File.WriteAllText("test.txt", str);
 29
Author: Flynn1179,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-11-22 09:37:42

Necesita escribir todas las líneas que lee en el archivo de salida, incluso si no las cambia.

Algo como:

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

Si desea realizar esta operación en su lugar, entonces la forma más fácil es usar un archivo de salida temporal y al final reemplazar el archivo de entrada con la salida.

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

(Intentar realizar operaciones de actualización en el medio del archivo de texto es bastante difícil de hacer bien porque siempre tener el reemplazo de la misma longitud es difícil dada la mayoría de las codificaciones son anchura variable.)

EDITAR: En lugar de dos operaciones de archivo para reemplazar el archivo original, es mejor usar File.Replace("input.txt", "output.txt", null). (Véase MSDN .)

 21
Author: Richard,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-03-01 07:51:12

Es probable que tenga que extraer el archivo de texto en la memoria y luego hacer los reemplazos. A continuación, tendrá que sobrescribir el archivo utilizando el método que conoce claramente. Así que primero:

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

Luego puede recorrer y reemplazar el texto en la matriz.

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

Este método le da cierto control sobre las manipulaciones que puede hacer. O, simplemente puede hacer el reemplazo en una línea

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

Espero que esto ayude.

 7
Author: MoonKnight,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-11-22 09:39:06

Así es como lo hice con un archivo GB múltiple: Usé 2 maneras diferentes, la primera: leyendo el archivo en memoria y usando Regex Replace o String Replace. Luego anexo toda la cadena a un archivo temporal.

La segunda es leyendo el archivo temporal línea por línea y construyendo manualmente cada línea usando StringBuilder y anexando cada línea procesada al archivo de resultados.

El primer método funciona bien para reemplazos generales de expresiones regulares, pero acapara la memoria si intenta hacer hacer Regex.Coincidencias en un archivo grande.

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

//note: don't use File.AppendAllText, it opens the file every time. Instead open StreamWriter in the beginning and write to it.
                   // 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
Author: live-love,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-07-10 18:00:27