Text replacer Learn programming C#



Lesson:

File Management


Exercise:

Text replacer


Objetive:

Create a program to replace words in a text file, saving the result into a new file.

The file, the word to search and word to replace it with must be given as parameters:

replace file.txt hello goodbye

The new file would be named "file.txt.out" and contain all the appearances of "hello" replaced by "goodbye".


Code:

using System;
using System.IO;
namespace Replace
{
    class Program
    {
        static void Main(string[] args)
        {
            ReplaceTextFile("file.txt", "Hola", "hola");
        }

        public static void ReplaceTextFile(string urlFile, string textReplace, string newText)
        {
            StreamReader myfileRd = File.OpenText(urlFile); ;
            StreamWriter myfileWr = File.CreateText("file.txt.out"); ;
            string line = " ";
            do
            {
                line = myfileRd.ReadLine();
                if (line != null)
                {
                    line = line.Replace(textReplace, newText);
                    myfileWr.WriteLine(line);
                }
            }
            while (line != null);
            myfileWr.Close();
            myfileRd.Close();
        }
    }
}



Juan A. Ripoll - Systems Tutorials and Programming Courses ©  All rights reserved.  Legal Conditions.