shavit
shavit

Reputation: 1063

Overwriting a string in a FileStream

The code I have is:

string sMD5Hash = sb.ToString();

using(Stream stream = new FileStream(sFile, FileMode.OpenOrCreate))
{
    stream.Seek(5, SeekOrigin.Begin);
    stream.Write(Encoding.ASCII.GetBytes(sMD5Hash), 0, sMD5Hash.Length);
}

What I'm trying to do is, seek to 5 and start writing my string there. Not regular writing because it will push the next bytes forward. But instead, I want to overwrite the bytes. How could I do it?

Upvotes: 2

Views: 1482

Answers (1)

Mostafiz
Mostafiz

Reputation: 7352

Make FileStream FileMode.OpenOrCreate and FileAccess.ReadWrite

using (Stream stream = new FileStream(sFile, FileMode.OpenOrCreate, FileAccess.ReadWrite))
{
    stream.Seek(5, SeekOrigin.Begin);
    stream.Write(Encoding.ASCII.GetBytes(sMD5Hash), 0, sMD5Hash.Length);
}

Upvotes: 2

Related Questions