123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125 |
- using System;
- using System.Collections.Generic;
- using System.IO;
- using System.Runtime.InteropServices;
- using System.Text;
- using Microsoft.Win32.SafeHandles;
- namespace DiskAccessLibrary
- {
-
-
-
-
-
- public class FileStreamEx : FileStream
- {
- [DllImport("Kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
- static extern bool ReadFile(SafeFileHandle handle, byte[] buffer, uint numberOfBytesToRead, out uint numberOfBytesRead, IntPtr lpOverlapped);
- private bool m_releaseHandle = true;
- public FileStreamEx(SafeFileHandle handle, FileAccess access) : base(handle, access)
- {
- }
-
-
- public override int Read(byte[] array, int offset, int count)
- {
- uint result;
- if (offset == 0)
- {
- ReadFile(this.SafeFileHandle, array, (uint)count, out result, IntPtr.Zero);
- }
- else
- {
- byte[] buffer = new byte[count];
- ReadFile(this.SafeFileHandle, buffer, (uint)buffer.Length, out result, IntPtr.Zero);
- Array.Copy(buffer, 0, array, offset, buffer.Length);
- }
- if (count == result)
- {
- return (int)result;
- }
- else
- {
- int errorCode = Marshal.GetLastWin32Error();
- string message = String.Format("Could not read from position {0} the requested number of bytes ({1}).", this.Position, count);
- ThrowIOError(errorCode, message);
- return 0;
- }
- }
- internal static void ThrowIOError(int errorCode, string defaultMessage)
- {
- if (errorCode == (int)Win32Error.ERROR_ACCESS_DENIED)
- {
-
- throw new UnauthorizedAccessException(defaultMessage);
- }
- else if (errorCode == (int)Win32Error.ERROR_SHARING_VIOLATION)
- {
- throw new SharingViolationException(defaultMessage);
- }
- else if (errorCode == (int)Win32Error.ERROR_SECTOR_NOT_FOUND)
- {
- string message = defaultMessage + " The sector does not exist.";
- throw new IOException(message, (int)Win32Error.ERROR_SECTOR_NOT_FOUND);
- }
- else if (errorCode == (int)Win32Error.ERROR_CRC)
- {
- throw new IOException("Data errorCode (cyclic redundancy check).", (int)Win32Error.ERROR_CRC);
- }
- else if (errorCode == (int)Win32Error.ERROR_NO_SYSTEM_RESOURCES)
- {
- throw new OutOfMemoryException();
- }
- else
- {
- string message = defaultMessage + String.Format(" Win32 Error: {0}", errorCode);
- throw new IOException(message, errorCode);
- }
- }
-
- public override int ReadByte()
- {
- throw new NotImplementedException("Cannot read a single byte from disk");
- }
- public void Close(bool releaseHandle)
- {
- m_releaseHandle = releaseHandle;
- this.Close();
- }
-
-
-
- protected override void Dispose(bool disposing)
- {
- if (m_releaseHandle)
- {
- base.Dispose(disposing);
- }
- else
- {
- try
- {
- this.Flush();
- }
- catch
- {
- }
- }
- }
- }
- }
|