using System;
using System.IO;
//范例:FileStream类型派生自实现了Close方法和无参的IDisposable.Dispose方法的Stream类型,
// FileStream类型简单重写了Dispose方法,它接受一个Boolean参数来释放Handle字段包装的非托管文件资源。
public sealed class Program
{
#if Version1
public static void Main() {
// Create the bytes to write to the temporary file.
Byte[] bytesToWrite = new Byte[] { 1, 2, 3, 4, 5 };
// Create the temporary file.
FileStream fs = new FileStream("Temp.dat", FileMode.Create);
// Write the bytes to the temporary file.
fs.Write(bytesToWrite, 0, bytesToWrite.Length);
// Explicitly close the file when done writing to it.
//如果注释掉下面一行,则文件基本上不可能删除。
((IDisposable) fs).Dispose();
// Delete the temporary file.
File.Delete("Temp.dat"); // This always works now
}
#endif
#if Version2
public static void Main()
{
// Create the bytes to write to the temporary file.
Byte[] bytesToWrite = new Byte[] { 1, 2, 3, 4, 5 };
// Create the temporary file.
FileStream fs = new FileStream("Temp.dat", FileMode.Create);
try
{
// Write the bytes to the temporary file.
fs.Write(bytesToWrite, 0, bytesToWrite.Length);
}
finally
{
// Explicitly close the file when done writing to it.
if (fs != null)
((IDisposable)fs).Dispose();//或者fs.Close();
}
// Delete the temporary file.
File.Delete("Temp.dat"); // This always works now.
}
#endif
}