1

Hi everyone beginner here looking for some advice with a program I'm writing in C#. I need to be able to open a text document, read the first line of text (that is not blank), save this line of text to another text document and finally overwrite the read line with an empty line.

This is what I have so far, everything works fine until the last part where I need to write a blank line to the original text document, I just get a full blank document. Like I mentioned above I'm new to C# so I'm sure there is an easy solution to this but I can't figure it out, any help appreciated:

try
            {
                StreamReader sr = new StreamReader(@"C:\Users\Stephen\Desktop\Sample.txt");

                line = sr.ReadLine();

                while (line == "")
                {
                    line = sr.ReadLine();
                }
                sr.Close();
                string path = (@"C:\Users\Stephen\Desktop\new.txt");
                if (!File.Exists(path))
                {
                    File.Create(path).Dispose();
                    TextWriter tw = new StreamWriter(path);
                    tw.WriteLine(line);
                    tw.Close();
                }
                else if (File.Exists(path))
                {
                    TextWriter tw = new StreamWriter(path, true);
                    tw.WriteLine(line);
                    tw.Close();
                }
                StreamWriter sw = new StreamWriter(@"C:\Users\Stephen\Desktop\Sample.txt");
                int cnt1 = 0;
                while (cnt1 < 1)
                {
                    sw.WriteLine("");
                    cnt1 = 1;
                }
                sw.Close();

            }
            catch (Exception e)
            {
                Console.WriteLine("Exception: " + e.Message);
            }
            finally
            {
                Console.WriteLine("Executing finally block.");
            }
        else
            Console.WriteLine("Program Not Installed");
        Console.ReadLine();
tuxedozombie
  • 181
  • 1
  • 2
  • 12
  • 1
    You might want to use the `using` keyword a bit in here. This doesn't answer your question, and I don't think you've missed anything, but it's a good habit to get into. It's easy to forget to close or dispose an object, and that can be a really frustrating error to encounter. – Matthew Haugen Jul 15 '14 at 09:36
  • You are overwriting your line variable. Try either File.ReadAllLines, or build your target file within your while loop. As @Matthew has said, wrap that with a using block to take care of the disposing. You also don't need the File checking stuff, a StreamWriter takes options to overwrite an existing file. – atom.gregg Jul 15 '14 at 09:39

2 Answers2

1

Unfortunately, you do have to go through the painstaking process of rewriting the file. In most cases, you could get away with loading it into memory and just doing something like:

string contents = File.ReadAllText(oldFile);
contents = contents.Replace("bad line!", "good line!");
File.WriteAllText(newFile, contents);

Remember that you'll have to deal with the idea of line breaks here, since string.Replace doesn't innately pay attention only to whole lines. But that's certainly doable. You could also use a regex with that approach. You can also use File.ReadAllLines(string) to read each line into an IEnumerable<string> and test each one while you write them back to the new file. It just depends on what exactly you want to do and how precise you want to be about it.

using (var writer = new StreamWriter(newFile))
{
    foreach (var line in File.ReadAllLines(oldFile))
    {
        if (shouldInsert(line))
            writer.WriteLine(line);
    }
}

That, of course, depends on the predicate shouldInsert, but you can modify that as you see so fit. But the nature of IEnumerable<T> should make that relatively light on resources. You could also use a StreamReader for a bit lower-level of support.

using (var writer = new StreamWriter(newFile))
using (var reader = new StreamReader(oldFile))
{
    string line;
    while ((line = reader.ReadLine()) != null)
    {
        if (shouldInsert(line))
            writer.WriteLine(line);
    }
}

Recall, of course, that this could leave you with an extra, empty line at the end of the file. I'm too tired to say that with the certainty I should be able to, but I'm pretty sure that's the case. Just keep an eye out for that, if it really matters. Of course, it normally won't.

That all said, the best way to do it would be to have a bit of fun and do it without wasting the memory, by writing a function to read the FileStream in and write out the appropriate bytes to your new file. That's, of course, the most complicated and likely over-kill way, but it'd be a fun undertaking.

Matthew Haugen
  • 12,916
  • 5
  • 38
  • 54
  • So ReadAllText is fine for reading a full text document but for just reading the first line, how would i go about doing that? – tuxedozombie Jul 15 '14 at 09:52
0

See: Append lines to a file using a StreamWriter

Add true to the StreamWriter constructor to set it to "Append" mode. Note that this adds a line at the bottom of the document, so you may have to fiddle a bit to insert or overwrite it at the top instead.

And see: Edit a specific Line of a Text File in C#

Apparently, it's not that easy to just insert or overwrite a single line and the usual method is just to copy all lines while replacing the one you want and writing every line back to the file.

Community
  • 1
  • 1
Davio
  • 4,609
  • 2
  • 31
  • 58