Thursday, July 20, 2006

Beware of the Stream.SetLength() Method

The SetLength() method of the System.IO.Stream class, which is an abstract class for many derived classes, actually truncates a file or stream to the size, in bytes, specified by the argument passed to it whether or not you call the Write() or WriteByte() methods.

The following code will truncate the file to 10 bytes.

using (FileStream fs = new FileStream(@"C:\boot.ini", FileMode.Open)) { fs.SetLength(10); // Oops, we just truncated the boot.ini file to 10 characters!!!!! int intByte = fs.ReadByte(); while (intByte > -1) { this.txtStatus.Text += Encoding.ASCII.GetString(new byte[] {(byte)intByte}); intByte = fs.ReadByte(); } } More information about the System.IO.Stream.SetLength() method here.

No comments: