-2

I know this has been asked a few times, but I have seen a lot of regex etc., and I'm sure there is another way to do this with just a stream reader/writer. Below is my code. I'm trying to replace "tea" with the word "cabbage". Can somebody help? I believe I have the wrong syntax.

namespace Week_9_Exer_4
{
    class TextImportEdit
    {
        public void EditorialControl()
        {
            string fileName;
            string lineReadFromFile;


            Console.WriteLine("");
            // Ask for the name of the file to be read
            Console.Write("Which file do you wish to read? ");
            fileName = Console.ReadLine();
            Console.WriteLine("");

            // Open the file for reading
            StreamReader fileReader = new StreamReader("C:\\Users\\Greg\\Desktop\\Programming Files\\story.txt");

            // Read the lines from the file and display them
            // until a null is returned (indicating end of file)
            lineReadFromFile = fileReader.ReadLine();

            Console.WriteLine("Please enter the word you wish to edit out: ");
            string editWord = Console.ReadLine();            

            while (lineReadFromFile != null)
            {
                Console.WriteLine(lineReadFromFile);
                lineReadFromFile = fileReader.ReadLine();
            }

            String text = File.ReadAllText("C:\\Users\\Greg\\Desktop\\Programming Files\\story.txt");
            fileReader.Close();

            StreamWriter fileWriter = new StreamWriter("C:\\Users\\Greg\\Desktop\\Programming Files\\story.txt", false);
            string newText = text.Replace("tea", "cabbage");
            fileWriter.WriteLine(newText);
            fileWriter.Close();

        }
    }
}
Cᴏʀʏ
  • 105,112
  • 20
  • 162
  • 194
Harvey993
  • 41
  • 1
  • 1
  • 4
  • 2
    " Can somebody help i believe i have the wrong syntax" - is not a real question. – Mitch Wheat Dec 01 '14 at 23:13
  • What error msg do you get? – MatthewMartin Dec 01 '14 at 23:14
  • 1
    Also, only 3 lines here matter, ReadAllText, replace, & write to the fileWriter. (with respect to tea and cabbage) – MatthewMartin Dec 01 '14 at 23:15
  • 1
    What is the problem exactly? Have you tried setting a breakpoint on `string newText = ...` to see if it's getting assigned the correct value? – Arian Motamedi Dec 01 '14 at 23:16
  • i dont get an error, it just doesn't replace the word tea with the word cabbage in my txt file, am i simply doing it wrong? what should i research to get this correct? – Harvey993 Dec 01 '14 at 23:17
  • I haven't tested it, but I think you may just need to Dispose() the fileWriter. This tutorial says there isn't much set up to StreamWriter. http://www.dotnetperls.com/streamwriter – MatthewMartin Dec 01 '14 at 23:19
  • Note that `string.Replace()` is *case-sensitive*. Try something like `newText = Regex.Replace(text, "tea", "cabbage", RegexOptions.Compiled | RegexOptions.IgnoreCase);` – Arian Motamedi Dec 01 '14 at 23:21
  • thankyou all for your replies, i will have a go at solving however I can and let you know what my problem, thanks:) – Harvey993 Dec 01 '14 at 23:24
  • okay so i had a go at this : string fileName = @"C:\Users\Greg\Desktop\Programming Files\story.txt"; File.WriteAllText(fileName, File.ReadAllText(fileName).Replace("tea", "cabbage")); and it replaces the words, however im getting a IOException, i understand that you can catch an exception? However isnt this bad practice? – Harvey993 Dec 01 '14 at 23:28
  • @Harvey993: Make sure you don't have the file open in a text editor while you run your code. – Cᴏʀʏ Dec 01 '14 at 23:37
  • hi cory , i didnt have the file open, i am going try the second way you suggested, it seems a lot better/faster. and is a lot more user friendly to understand the process. thankyou! – Harvey993 Dec 01 '14 at 23:42

2 Answers2

3

If you don't care about memory usage:

string fileName = @"C:\Users\Greg\Desktop\Programming Files\story.txt";
File.WriteAllText(fileName, File.ReadAllText(fileName).Replace("tea", "cabbage"));

If you have a multi-line file that doesn't randomly split words at the end of the line, you could modify one line at a time in a more memory-friendly way:

// Open a stream for the source file
using (var sourceFile = File.OpenText(fileName))
{
    // Create a temporary file path where we can write modify lines
    string tempFile = Path.Combine(Path.GetDirectoryName(fileName), "story-temp.txt");
    // Open a stream for the temporary file
    using (var tempFileStream = new StreamWriter(tempFile)) 
    {
        string line;
        // read lines while the file has them
        while ((line = sourceFile.ReadLine()) != null) 
        {
            // Do the word replacement
            line = line.Replace("tea", "cabbage");
            // Write the modified line to the new file
            tempFileStream.WriteLine(line);
        }
    }
}
// Replace the original file with the temporary one
File.Replace("story-temp.txt", "story.txt", null);
Cᴏʀʏ
  • 105,112
  • 20
  • 162
  • 194
  • thanks i will try this and let you know the results, i do not care about memory usage as of now, im still a huge rookie so i dont think it applies yet. Thanks – Harvey993 Dec 01 '14 at 23:20
0

In the end i used this : Hope it can help out others

      public List<string> EditorialResponse(string fileName, string searchString,                  string replacementString)
    {
        List<string> list = new List<string>();
        using (StreamReader reader = new StreamReader(fileName))
        {
            string line;
            while ((line = reader.ReadLine()) != null)
            {
                line = line.Replace(searchString, replacementString);
                list.Add(line);
                Console.WriteLine(line);
            }
            reader.Close();
        }
        return list;
    }


}

class Program
{
    static void Main(string[] args)
    {
        TextImportEdit tie = new TextImportEdit();

        List<string> ls = tie.EditorialResponse(@"C:\Users\Tom\Documents\Visual Studio 2013\story.txt", "tea", "cockrel");

        StreamWriter writer = new StreamWriter(@"C:\Users\Tom\Documents\Visual Studio 2013\story12.txt");
        foreach (string line in ls)
        {
            writer.WriteLine(line);
        }
        writer.Close();


    }
}

}

Harvey993
  • 41
  • 1
  • 1
  • 4