Arsen Zahray
Arsen Zahray

Reputation: 25367

How to clear file content without closing it?

I've got a file, consisting of a single line, which I intend to write quite often. Because of this, I don't want to close and re-open it over and aver again. Instead I want to call something that would erase file content.

One way to accomplish what I have in mind is by doing something like this:

        int i0 = 0;
        using (var f = File.OpenWrite("testfile.txt"))
        {
            while (true)
            {
                f.Position = 0;
                using (var sw = new StreamWriter(f, Encoding.UTF8, 1024, true))
                {
                    if (i0 == 1)
                    {
                        sw.WriteLine("short line");
                        break;
                    }
                    if (i0==0)
                    {
                        sw.WriteLine("this is a veeeery long test line");
                        i0++;
                    }


                    sw.Flush();
                }
            }
        }

However, this will result in file with following content:

short line
eeery long test line

While I can work with this (I only need the content of the first line anyway), it feels messy.

Instead, I want to end up with file content:

short line

Is there a better way to do this?

Upvotes: 0

Views: 296

Answers (2)

LB2
LB2

Reputation: 4860

You can use FileStream.SetLength() to truncate, as well as FileStream.Position and/or FileStream.Seek() to move back to the beginning of file. This would not require expensive close and reopen of the stream.

Upvotes: 2

Sector95
Sector95

Reputation: 641

You could rewrite the file: http://msdn.microsoft.com/en-us/library/92e05ft3%28v=vs.110%29.aspx

File.WriteAllLines(String filePath, String[] linesToWrite);

This does open and close the file, however.

Upvotes: 0

Related Questions