shavit shavit - 3 months ago 10
C# Question

Overwriting a string in a stream

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?

Answer

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);
}