Thursday, August 03, 2006

Check DriveInfo.IsReady Before Using DriveInfo Members

I noticed that calling various members of the DriveInfo class will cause an error if the drive is not ready; therefore, check the IsReady property to determine if the drive is ready accordingly.

foreach (DriveInfo drive in DriveInfo.GetDrives()) { if (drive.IsReady) this.txtStatus.Text += drive.Name + "; " + drive.DriveFormat + "\r\n"; }

Also, all types of optical drives have a DriveType enumeration of CDRom.

Wednesday, July 26, 2006

New .Net 2.0 Stream.Dispose Methods

The System.IO.Stream abstract class now implements the IDisposable interface fully (explicitly and non-explicitly). What did it do before that?! Stream implemented the interface explicitly, making only interface instances able to call Dispose(). Before .Net 2.0, it was up to you to implement the IDisposable interface and clean up your derived class' resources via an interface object. You can now call Dispose() methods directly from an object that isn't cast to IDisposable.

New method: FileStream fs = new FileStream(@"C:\boot.ini", FileMode.Open, FileAccess.Read) fs.Dispose(); // or simply... - the better practice/pattern using (FileStream fs = new FileStream(@"C:\boot.ini", FileMode.Open, FileAccess.Read)) { // code ... } Old method: FileStream fs = new FileStream(@"C:\boot.ini", FileMode.Open, FileAccess.Read) IDisposable disp = (IDisposable) fs; disp.Dispose();

Tuesday, July 25, 2006

New .Net 2.0 Stream.ReadTimout and Stream.WriteTimout

The new .Net 2.0 Stream.ReadTimout and Stream.WriteTimout properties don't work with all derived classes, such as FileStream. Therefore, always ensure that you check the Stream.CanTimeout property before calling any of these new properties. using (FileStream fs = new FileStream( @"C:\boot.ini", FileMode.Open, FileAccess.Read)) { if (fs.CanTimeout) { fs.ReadTimeout = 1; // 1 millisecond fs.WriteTimeout = 1; // 1 millisecond } int intByte = fs.ReadByte(); while (intByte > -1) { this.txtStatus.Text += Encoding.ASCII.GetString(new byte[] {(byte)intByte}); intByte = fs.ReadByte(); } }

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.