Dispose code example
Example 1: dispose method in c# with example
using Microsoft.Win32.SafeHandles;
using System;
using System.Runtime.InteropServices;
public class DisposableStreamResource : IDisposable
{
protected const uint GENERIC_READ = 0x80000000;
protected const uint FILE_SHARE_READ = 0x00000001;
protected const uint OPEN_EXISTING = 3;
protected const uint FILE_ATTRIBUTE_NORMAL = 0x80;
private const int INVALID_FILE_SIZE = unchecked((int)0xFFFFFFFF);
[DllImport("kernel32.dll", EntryPoint = "CreateFileW", CharSet = CharSet.Unicode)]
protected static extern SafeFileHandle CreateFile(
string lpFileName, uint dwDesiredAccess,
uint dwShareMode, IntPtr lpSecurityAttributes,
uint dwCreationDisposition, uint dwFlagsAndAttributes,
IntPtr hTemplateFile);
[DllImport("kernel32.dll")]
private static extern int GetFileSize(
SafeFileHandle hFile, out int lpFileSizeHigh);
private bool _disposed = false;
private readonly SafeFileHandle _safeHandle;
private readonly int _upperWord;
public DisposableStreamResource(string fileName)
{
if (string.IsNullOrWhiteSpace(fileName))
{
throw new ArgumentException("The fileName cannot be null or an empty string");
}
_safeHandle = CreateFile(
fileName, GENERIC_READ, FILE_SHARE_READ, IntPtr.Zero,
OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, IntPtr.Zero);
Size = GetFileSize(_safeHandle, out _upperWord);
if (Size == INVALID_FILE_SIZE)
{
Size = -1;
}
else if (_upperWord > 0)
{
Size = (((long)_upperWord) << 32) + Size;
}
}
public long Size { get; }
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
if (_disposed)
{
return;
}
if (disposing)
{
_safeHandle?.Dispose();
}
_disposed = true;
}
}
Example 2: dispose method in c# with example
protected virtual void Dispose(bool disposing)
{
}
Example 3: dispose method in c# with example
using Microsoft.Win32.SafeHandles;
using System;
using System.Runtime.InteropServices;
public class DisposableStreamResource2 : DisposableStreamResource
{
protected const uint GENERIC_WRITE = 0x40000000;
protected const uint OPEN_ALWAYS = 4;
[DllImport("kernel32.dll")]
protected static extern bool WriteFile(
SafeFileHandle safeHandle, string lpBuffer,
int nNumberOfBytesToWrite, out int lpNumberOfBytesWritten,
IntPtr lpOverlapped);
private bool _disposed = false;
private bool _created = false;
private SafeFileHandle _safeHandle;
private readonly string _fileName;
public DisposableStreamResource2(string fileName) : base(fileName) => _fileName = fileName;
public void WriteFileInfo()
{
if (!_created)
{
_safeHandle = CreateFile(
@".\FileInfo.txt", GENERIC_WRITE, 0, IntPtr.Zero,
OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, IntPtr.Zero);
_created = true;
}
string output = $"{_fileName}: {Size:N0} bytes\n";
_ = WriteFile(_safeHandle, output, output.Length, out _, IntPtr.Zero);
}
protected override void Dispose(bool disposing)
{
if (_disposed)
{
return;
}
if (disposing)
{
_safeHandle?.Dispose();
}
_disposed = true;
base.Dispose(disposing);
}
}