0

I have the following class in .NetCore console application. This class has FileStream and SafeFileHandle fields. I am using pInvoke to create file and assign the result to SafeFileHandle instance.

Does this class should have Finalizer implementation?

 public class MyClass : IDisposable
 {
        private SafeFileHandle m_handleValue;
        private FileStream m_fileStream;


        [DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
        private static extern SafeFileHandle CreateFile(string lpFileName, uint dwDesiredAccess,
            uint dwShareMode, IntPtr lpSecurityAttributes, uint dwCreationDisposition,
            uint dwFlagsAndAttributes, IntPtr hTemplateFile);



        public void CreateFile()
        {
            m_handleValue = CreateFile(m_path,
                GENERIC_WRITE | GENERIC_READ,
                SHARE_MODE_READ_WRITE, 
                IntPtr.Zero,
                OPEN_EXISTING,
                FILE_FLAG_NO_BUFFERING | FILE_FLAG_WRITE_THROUGH, 
                IntPtr.Zero);
            m_fileStream = new FileStream(m_handleValue, FileAccess.ReadWrite);
        }

        public void CloseStream()
        {
            m_handleValue.Close();
        }

        public void Write(long offset, byte[] data)
        {
            m_fileStream.Seek(offset, SeekOrigin.Begin);
            m_fileStream.Write(data, 0, data.Length);
        }

        public byte[] Read(long offset, int length)
        {
            var buffer = new byte[length];
            m_fileStream.Seek(offset, SeekOrigin.Begin);
            m_fileStream.Read(buffer, 0, length);

            return buffer;
        }

    public void Dispose()
    {
        m_handleValue?.Dispose();
        m_fileStream?.Dispose();
    }
}
Yaniv daye
  • 73
  • 7
  • 1
    Recommended reading: https://stackoverflow.com/a/898867/11683 – GSerg Apr 22 '20 at 12:12
  • You ought to consider making FileStream the base class of this class. FileStream implements the disposable pattern, forces you to get it right. If that is not appropriate then either `sealed` the class or implement the disposable pattern yourself. – Hans Passant Apr 22 '20 at 12:55

1 Answers1

1

No, one of the main points of using SafeFileHandle is it contains the finalizer that cleans up the unmanaged resource related to the handle.

Damien_The_Unbeliever
  • 234,701
  • 27
  • 340
  • 448