3

I need to add a header to a text file using this function:

private static void WriteFile(string fileToRead, string fileToWrite, string mySearchString)
    {
        using (var sr = new StreamReader(fileToRead))
        using (var sw = new StreamWriter(fileToWrite, true))
        {
            var count = 1;

            while (sr.Peek() != -1)
            {
                var line = sr.ReadLine();

             /*   if (count == 3)
                {
                    sw.WriteLine(line);
                } */
                if (count > 4)
                {
                    if (line != null && line.Contains(mySearchString))
                    {
                        sw.WriteLine(line);
                    }
                }

                count++;
            }

For example: put the string "blah blah blah" to the top of the text file without overwriting the text that is there. I need the code to be implemented inside the function above

Keep in mind I only want the header written once. I am iterating through multiple text files using this function and appending to a new text file but only need the header written one time not everytime a text file is opened for parsing.

SlopTonio
  • 1,105
  • 1
  • 16
  • 39
  • Maybe you should use sr.EndOfStream rather than sr.Peek() – Casperah Dec 26 '13 at 19:44
  • @varocarbas that writes it multiple times because im looping through multiple text files and appending it into 1. Each time it opens a text file it will write blah blah blah but I only want it done once – SlopTonio Dec 26 '13 at 19:45
  • Yeah, I realised that you were appending the file and that's why I deleted my comment. – varocarbas Dec 26 '13 at 19:47

2 Answers2

3

You code should look like this:

    using (var sr = new StreamReader(fileToRead))
    using (var sw = new StreamWriter(fileToWrite, true))
    {
        if (sw.BaseStream.Position == 0)
            sw.WriteLine("bla bla...");  // Only write header in a new empty file.

        var count = 1;

Good luck with your quest.

Casperah
  • 4,504
  • 1
  • 19
  • 13
0

You can try something like that:

StringBuilder sb = new StringBuilder(File.ReadAllText(fileToWrite));
sb.Insert(0, line);
sw.Write(sb.ToString());
w.b
  • 11,026
  • 5
  • 30
  • 49