/* * Process Hacker - * file handle * * Copyright (C) 2009 wj32 * * This file is part of Process Hacker. * * Process Hacker is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Process Hacker is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Process Hacker. If not, see . */ using System; using System.Runtime.InteropServices; namespace ProcessHacker { public partial class Win32 { /// /// Represents a handle to a file. /// public class FileHandle : Win32Handle { public FileHandle(string fileName, FILE_RIGHTS desiredAccess, FILE_SHARE_MODE shareMode, FILE_CREATION_DISPOSITION creationDisposition) { this.Handle = CreateFile(fileName, desiredAccess, shareMode, 0, creationDisposition, 0, 0); if (this.Handle == 0) ThrowLastWin32Error(); } public FileHandle(string fileName, FILE_RIGHTS desiredAccess, FILE_SHARE_MODE shareMode) : this(fileName, desiredAccess, shareMode, FILE_CREATION_DISPOSITION.OpenExisting) { } public FileHandle(string fileName, FILE_RIGHTS desiredAccess) : this(fileName, desiredAccess, FILE_SHARE_MODE.Exclusive) { } /// /// Sends an I/O control message to the device's associated driver. /// /// The device-specific control code. /// The input. /// The output buffer. /// The bytes returned in the output buffer. public int IoControl(uint controlCode, byte[] inBuffer, byte[] outBuffer) { int returnBytes; byte[] inArr = inBuffer; int inLen = inArr != null ? inBuffer.Length : 0; byte[] outArr = outBuffer; int outLen = outArr != null ?outBuffer.Length : 0; if (!DeviceIoControl(this, (int)controlCode, inArr, inLen, outArr, outLen, out returnBytes, 0)) ThrowLastWin32Error(); return returnBytes; } /// /// Reads data from the file. /// /// The buffer to store the data in. /// The number of bytes read from the file. public int Read(byte[] buffer) { int bytesRead; if (!ReadFile(this, buffer, buffer.Length, out bytesRead, 0)) ThrowLastWin32Error(); return bytesRead; } /// /// Reads data from the file. /// /// The length to read. /// The read data. public byte[] Read(int length) { byte[] buffer = new byte[length]; this.Read(buffer); return buffer; } /// /// Writes data to the file. /// /// The data. /// The number of bytes written to the file. public int Write(byte[] buffer) { int bytesWritten; if (!WriteFile(this, buffer, buffer.Length, out bytesWritten, 0)) ThrowLastWin32Error(); return bytesWritten; } } } }