Reuben Ward
Reuben Ward

Reputation: 99

C# StreamWriter writing over a current text file

I have a text file with the following text inside:

[username][0]

I have opened the file using StreamWriter and I want to change the 0 to a 1 using the StreamWriter.Write Method. How can I do this?

Upvotes: 1

Views: 568

Answers (1)

jmcilhinney
jmcilhinney

Reputation: 54417

If you know the exact byte position of the character(s) you want to overwrite then you can do something like this:

using (var writer = new StreamWriter(filePath))
{
    writer.BaseStream.Seek(bytePos, SeekOrigin.Begin);
    writer.Write('1');
}

If you don't know the exact byte position then you could do something like this:

using (var file = new FileStream(filePath, FileMode.Open))
using (var reader = new StreamReader(file))
using (var writer = new StreamWriter(file))
{
    var openBracketCount = 0;

    // Keep reading characters until the second open bracket is found.
    do
    {
        var ch = Convert.ToChar(reader.Read());

        if (ch == '[')
        {
            openBracketCount++;
        }
    } while (openBracketCount < 2);

    writer.Write('1');
}

Upvotes: 1

Related Questions