Search code examples
c#text-filesstreamreaderstreamwriter

How to edit a text file in c# with StreamWriter?


I have a method to edit a word from a text file file and display it on the command prompt. Now I an trying to make a method to edit a word from a text file and write it to a new file. I would also like to mention that I cannot use the File or Regex class since I am not allowed to use it for my assignment. Here is my code for the StreamReader:

public void EditorialControl(string fileName, string word, string replacement)
{            
    List<string> list = new List<string>();
    using (StreamReader reader = new StreamReader(directory + fileName))
    {
        string line;
        while ((line = reader.ReadLine()) != null)
        {                    
            line = line.Replace(word, replacement);
            list.Add(line);
            Console.WriteLine(line);
        }
        reader.Close();
    }      
}

and here is my code so far for the StreamWriter:

public void EditorialResponse(string fileName, string word, string replacement, string saveFileName)
{
    using (StreamWriter writer = new StreamWriter(directory + saveFileName, true))
    {
        {
            string input = directory + fileName;
            string line = input.Replace(word, replacement);
            writer.Write(line);                     
        }
        writer.Close();
    }
}

what can I add to make the StreamWriter open a file, edit a word and write it to a new file or possibly use the StreamReader method to make these changes in StreamWriter? Thank you


Solution

  • Here...

    public void EditorialResponse(string fileName, string word, string replacement, string saveFileName)
    {
        StreamReader reader = new StreamReader(directory + fileName);
        string input = reader.ReadToEnd();
    
        using (StreamWriter writer = new StreamWriter(directory + saveFileName, true))
        {
            {
                string output = input.Replace(word, replacement);
                writer.Write(output);                     
            }
            writer.Close();
        }
    }