/// /// 获取磁盘扇区信息 /// /// G: public DriverLoader(string DirverName, long max_lba) { if (DirverName == null && DirverName.Trim().Length == 0) { return; } Console.WriteLine("Open disk: {0}", DirverName); SafeFileHandle _DirverHandle = CreateFileA(DirverName, GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE, IntPtr.Zero, OPEN_EXISTING, 0, IntPtr.Zero); try { _DirverStream = new FileStream(_DirverHandle, FileAccess.ReadWrite); } catch (Exception ex) { MessageBox.Show(ex.Message, _DirverHandle.ToString(), MessageBoxButtons.OK); while (true) { ; } } disk_max_lba = max_lba; Console.WriteLine("set max lba:{0}", max_lba); }
//<snippet4> private bool GetPrefsForUser() { try { //<Snippet15> // Retrieve an IsolatedStorageFile for the current Domain and Assembly. IsolatedStorageFile isoFile = IsolatedStorageFile.GetStore(IsolatedStorageScope.User | IsolatedStorageScope.Assembly | IsolatedStorageScope.Domain, null, null); IsolatedStorageFileStream isoStream = new IsolatedStorageFileStream("substituteUsername", System.IO.FileMode.Open, System.IO.FileAccess.Read, System.IO.FileShare.Read); //</Snippet15> // The code executes to this point only if a file corresponding to the username exists. // Though you can perform operations on the stream, you cannot get a handle to the file. try { SafeFileHandle aFileHandle = isoStream.SafeFileHandle; Console.WriteLine("A pointer to a file handle has been obtained. " + aFileHandle.ToString() + " " + aFileHandle.GetHashCode()); } catch (Exception e) { // Handle the exception. Console.WriteLine("Expected exception"); Console.WriteLine(e); } StreamReader reader = new StreamReader(isoStream); // Read the data. this.NewsUrl = reader.ReadLine(); this.SportsUrl = reader.ReadLine(); reader.Close(); isoFile.Close(); return(false); } catch (System.IO.FileNotFoundException) { // Expected exception if a file cannot be found. This indicates that we have a new user. return(true); } }
public override bool UnmountCurrentDiskImage() { if (mountedHandle != null) { Win32Error error = VirtDisk.DetachVirtualDisk(mountedHandle, VirtDisk.DETACH_VIRTUAL_DISK_FLAG.DETACH_VIRTUAL_DISK_FLAG_NONE, 0); if (error.Failed) { AutoMounter.Plugin.LogInfo($"WinVirtDisk: Failed to unmount disk from system {mountedHandle.ToString()}, {error.ToString()}"); AutoMounter.API.Dialogs.ShowErrorMessage("Failed to unmount disk from system", "AutoMounter"); } mountedHandle.Close(); mountedHandle = null; } return(true); }
/// <summary> /// Uses a series of API calls to locate a HID-class device /// by its Vendor ID and Product ID. /// Fills myDevicePathName with a path to device found, readHandle and writeHandle. Registers for Device Notifications (attached / detached type of events). /// </summary> /// /// <returns> /// True if the device is detected, False if not detected. /// </returns> private Boolean FindTheHid(Int32 myVendorID, Int32 myProductID) { Boolean someHidDevicesFound = false; String[] devicePathName = new String[128]; String functionName = ""; Guid hidGuid = Guid.Empty; Int32 memberIndex = 0; Boolean success = false; try { myDeviceDetected = false; Tracer.Trace(string.Format("FindTheHid(0x{0:X04}, 0x{1:X04})", myVendorID, myProductID)); // *** // API function: 'HidD_GetHidGuid // Purpose: Retrieves the interface class GUID for the HID class. // Accepts: 'A System.Guid object for storing the GUID. // *** Hid.HidD_GetHidGuid(ref hidGuid); functionName = "GetHidGuid"; Tracer.Trace(MyDebugging.ResultOfAPICall(functionName)); Tracer.Trace(" GUID for system HIDs: " + hidGuid.ToString()); // Fill an array with the device path names of all attached HIDs. someHidDevicesFound = MyDeviceManagement.FindDeviceFromGuid(hidGuid, ref devicePathName); // If there is at least one HID, attempt to read the Vendor ID and Product ID // of each device until there is a match or all devices have been examined. // // Fill myDevicePathName with a path to device found. if (someHidDevicesFound) { memberIndex = 0; // Tracer.Trace(" total number of HID devices: " + devicePathName.Length); // will be something like 128, a lot of empty paths there. do { // *** // API function: // CreateFile // Purpose: // Retrieves a handle to a device. // Accepts: // A device path name returned by SetupDiGetDeviceInterfaceDetail // The type of access requested (read/write). // FILE_SHARE attributes to allow other processes to access the device while this handle is open. // A Security structure or IntPtr.Zero. // A creation disposition value. Use OPEN_EXISTING for devices. // Flags and attributes for files. Not used for devices. // Handle to a template file. Not used. // Returns: a handle without read or write access. // This enables obtaining information about all HIDs, even system // keyboards and mice. // Separate handles are used for reading and writing. // *** if (!string.IsNullOrEmpty(devicePathName[memberIndex])) { Tracer.Trace(" trying HID device path '" + devicePathName[memberIndex] + "'"); hidHandle = FileIO.CreateFile(devicePathName[memberIndex], 0, FileIO.FILE_SHARE_READ | FileIO.FILE_SHARE_WRITE, IntPtr.Zero, FileIO.OPEN_EXISTING, 0, 0); functionName = "CreateFile"; Tracer.Trace(MyDebugging.ResultOfAPICall(functionName)); Tracer.Trace(" FindTheHid(): some HID device found, returned handle: " + hidHandle.ToString()); if (!hidHandle.IsInvalid) { // The returned handle is valid, // so find out if this is the device we're looking for. // Set the Size property of DeviceAttributes to the number of bytes in the structure. MyHid.DeviceAttributes.Size = Marshal.SizeOf(MyHid.DeviceAttributes); // *** // API function: // HidD_GetAttributes // Purpose: // Retrieves a HIDD_ATTRIBUTES structure containing the Vendor ID, // Product ID, and Product Version Number for a device. // Accepts: // A handle returned by CreateFile. // A pointer to receive a HIDD_ATTRIBUTES structure. // Returns: // True on success, False on failure. // *** success = Hid.HidD_GetAttributes(hidHandle, ref MyHid.DeviceAttributes); if (success) { Tracer.Trace(" HIDD_ATTRIBUTES structure filled without error."); Tracer.Trace(" Structure size: " + MyHid.DeviceAttributes.Size); Tracer.Trace(string.Format(" Vendor ID: 0x{0:X04}", MyHid.DeviceAttributes.VendorID)); Tracer.Trace(string.Format(" Product ID: 0x{0:X04}", MyHid.DeviceAttributes.ProductID)); Tracer.Trace(string.Format(" Version Number: 0x{0:X04}", MyHid.DeviceAttributes.VersionNumber)); // Find out if the device matches the one we're looking for. if ((MyHid.DeviceAttributes.VendorID == myVendorID) && (MyHid.DeviceAttributes.ProductID == myProductID)) { Tracer.Trace(" My device detected"); myDeviceDetected = true; // Save the DevicePathName for OnDeviceChange(). myDevicePathName = devicePathName[memberIndex]; } else { // It's not a match, so close the handle. Tracer.Trace(" (This is not My Device)"); myDeviceDetected = false; hidHandle.Close(); } } else { // There was a problem in retrieving the information. Tracer.Trace(" Error in filling HIDD_ATTRIBUTES structure."); myDeviceDetected = false; hidHandle.Close(); } } } // Keep looking until we find the device or there are no devices left to examine. memberIndex = memberIndex + 1; }while (!((myDeviceDetected || (memberIndex == devicePathName.Length)))); } if (myDeviceDetected) { // The device was detected. // Register to receive notifications if the device is removed or attached. success = MyDeviceManagement.RegisterForDeviceNotifications(myDevicePathName, WindowHandle, hidGuid, ref deviceNotificationHandle); Tracer.Trace("RegisterForDeviceNotifications = " + success); // Learn the capabilities of the device. MyHid.Capabilities = MyHid.GetDeviceCapabilities(hidHandle); if (success) { // Find out if the device is a system mouse or keyboard. hidUsage = MyHid.GetHidUsage(MyHid.Capabilities); // Get the Input report buffer size. GetInputReportBufferSize(); // Get handles to use in requesting Input and Output reports. readHandle = FileIO.CreateFile(myDevicePathName, FileIO.GENERIC_READ, FileIO.FILE_SHARE_READ | FileIO.FILE_SHARE_WRITE, IntPtr.Zero, FileIO.OPEN_EXISTING, FileIO.FILE_FLAG_OVERLAPPED, 0); functionName = "CreateFile, ReadHandle"; Tracer.Trace(MyDebugging.ResultOfAPICall(functionName)); Tracer.Trace(" FindTheHid(): success, returned handle: " + readHandle.ToString()); if (readHandle.IsInvalid) { exclusiveAccess = true; Tracer.Error("The device is a system " + hidUsage + ". Applications can access Feature reports only."); } else { writeHandle = FileIO.CreateFile(myDevicePathName, FileIO.GENERIC_WRITE, FileIO.FILE_SHARE_READ | FileIO.FILE_SHARE_WRITE, IntPtr.Zero, FileIO.OPEN_EXISTING, 0, 0); functionName = "CreateFile, WriteHandle"; Tracer.Trace(MyDebugging.ResultOfAPICall(functionName)); Tracer.Trace(" FindTheHid(): handle valid, returned handle: " + writeHandle.ToString()); // Flush any waiting reports in the input buffer. (optional) MyHid.FlushQueue(readHandle); } } } else { // The device wasn't detected. Tracer.Error(string.Format("My Device not found - need a HID with vendorId={0}, productId={1}.", vendorId, productId)); } return(myDeviceDetected); } catch (Exception ex) { Tracer.Error(ex); throw; } }
/// <summary> /// Uses a series of API calls to locate a HID-class device /// by its Vendor ID and Product ID. /// </summary> /// /// <returns> /// True if the device is detected, False if not detected. /// </returns> private Boolean FindTheHid() { Boolean deviceFound = false; String[] devicePathName = new String[ 128 ]; String functionName = ""; Guid hidGuid = Guid.Empty; Int32 memberIndex = 0; Int32 myProductID = 0; Int32 myVendorID = 0; Boolean success = false; try { myDeviceDetected = false; CloseCommunications(); // Get the device's Vendor ID and Product ID from the form's text boxes. GetVendorAndProductIDsFromTextBoxes( ref myVendorID, ref myProductID ); // *** // API function: 'HidD_GetHidGuid // Purpose: Retrieves the interface class GUID for the HID class. // Accepts: 'A System.Guid object for storing the GUID. // *** Hid.HidD_GetHidGuid( ref hidGuid ); functionName = "GetHidGuid"; Debug.WriteLine( MyDebugging.ResultOfAPICall( functionName ) ); Debug.WriteLine( " GUID for system HIDs: " + hidGuid.ToString() ); // Fill an array with the device path names of all attached HIDs. deviceFound = MyDeviceManagement.FindDeviceFromGuid( hidGuid, ref devicePathName ); // If there is at least one HID, attempt to read the Vendor ID and Product ID // of each device until there is a match or all devices have been examined. if ( deviceFound ) { memberIndex = 0; do { // *** // API function: // CreateFile // Purpose: // Retrieves a handle to a device. // Accepts: // A device path name returned by SetupDiGetDeviceInterfaceDetail // The type of access requested (read/write). // FILE_SHARE attributes to allow other processes to access the device while this handle is open. // A Security structure or IntPtr.Zero. // A creation disposition value. Use OPEN_EXISTING for devices. // Flags and attributes for files. Not used for devices. // Handle to a template file. Not used. // Returns: a handle without read or write access. // This enables obtaining information about all HIDs, even system // keyboards and mice. // Separate handles are used for reading and writing. // *** // Open the handle without read/write access to enable getting information about any HID, even system keyboards and mice. hidHandle = FileIO.CreateFile(devicePathName[memberIndex], 0, FileIO.FILE_SHARE_READ | FileIO.FILE_SHARE_WRITE, IntPtr.Zero, FileIO.OPEN_EXISTING, 0, 0); functionName = "CreateFile"; Debug.WriteLine( MyDebugging.ResultOfAPICall( functionName ) ); Debug.WriteLine( " Returned handle: " + hidHandle.ToString() ); if (!hidHandle.IsInvalid) { // The returned handle is valid, // so find out if this is the device we're looking for. // Set the Size property of DeviceAttributes to the number of bytes in the structure. MyHid.DeviceAttributes.Size = Marshal.SizeOf( MyHid.DeviceAttributes ); // *** // API function: // HidD_GetAttributes // Purpose: // Retrieves a HIDD_ATTRIBUTES structure containing the Vendor ID, // Product ID, and Product Version Number for a device. // Accepts: // A handle returned by CreateFile. // A pointer to receive a HIDD_ATTRIBUTES structure. // Returns: // True on success, False on failure. // *** success = Hid.HidD_GetAttributes(hidHandle, ref MyHid.DeviceAttributes); if ( success ) { Debug.WriteLine( " HIDD_ATTRIBUTES structure filled without error." ); Debug.WriteLine( " Structure size: " + MyHid.DeviceAttributes.Size ); Debug.WriteLine(" Vendor ID: " + Convert.ToString(MyHid.DeviceAttributes.VendorID, 16)); Debug.WriteLine(" Product ID: " + Convert.ToString(MyHid.DeviceAttributes.ProductID, 16)); Debug.WriteLine(" Version Number: " + Convert.ToString(MyHid.DeviceAttributes.VersionNumber, 16)); // Find out if the device matches the one we're looking for. if ( ( MyHid.DeviceAttributes.VendorID == myVendorID ) && ( MyHid.DeviceAttributes.ProductID == myProductID ) ) { Debug.WriteLine( " My device detected" ); // Display the information in form's list box. lstResults.Items.Add( "Device detected:" ); lstResults.Items.Add(" Vendor ID= " + Convert.ToString(MyHid.DeviceAttributes.VendorID, 16)); lstResults.Items.Add(" Product ID = " + Convert.ToString(MyHid.DeviceAttributes.ProductID, 16)); ScrollToBottomOfListBox(); myDeviceDetected = true; // Save the DevicePathName for OnDeviceChange(). myDevicePathName = devicePathName[ memberIndex ]; } else { // It's not a match, so close the handle. myDeviceDetected = false; hidHandle.Close(); } } else { // There was a problem in retrieving the information. Debug.WriteLine( " Error in filling HIDD_ATTRIBUTES structure." ); myDeviceDetected = false; hidHandle.Close(); } } // Keep looking until we find the device or there are no devices left to examine. memberIndex = memberIndex + 1; } while ( ! ( ( myDeviceDetected || ( memberIndex == devicePathName.Length ) ) ) ); } if ( myDeviceDetected ) { // The device was detected. // Register to receive notifications if the device is removed or attached. success = MyDeviceManagement.RegisterForDeviceNotifications( myDevicePathName, FrmMy.Handle, hidGuid, ref deviceNotificationHandle ); Debug.WriteLine( "RegisterForDeviceNotifications = " + success ); // Learn the capabilities of the device. MyHid.Capabilities = MyHid.GetDeviceCapabilities( hidHandle ); if ( success ) { // Find out if the device is a system mouse or keyboard. hidUsage = MyHid.GetHidUsage( MyHid.Capabilities ); // Get the Input report buffer size. GetInputReportBufferSize(); cmdInputReportBufferSize.Enabled = true; //Close the handle and reopen it with read/write access. hidHandle.Close(); hidHandle = FileIO.CreateFile(myDevicePathName, FileIO.GENERIC_READ | FileIO.GENERIC_WRITE, FileIO.FILE_SHARE_READ | FileIO.FILE_SHARE_WRITE, IntPtr.Zero, FileIO.OPEN_EXISTING, 0, 0); if ( hidHandle.IsInvalid ) { exclusiveAccess = true; lstResults.Items.Add( "The device is a system " + hidUsage + "." ); lstResults.Items.Add( "Windows 2000 and Windows XP obtain exclusive access to Input and Output reports for this devices." ); lstResults.Items.Add( "Applications can access Feature reports only." ); ScrollToBottomOfListBox(); } else { if (MyHid.Capabilities.InputReportByteLength > 0) { // Set the size of the Input report buffer. Byte[] inputReportBuffer = null; inputReportBuffer = new Byte[MyHid.Capabilities.InputReportByteLength]; fileStreamDeviceData = new FileStream(hidHandle, FileAccess.Read | FileAccess.Write, inputReportBuffer.Length, false); } if (MyHid.Capabilities.OutputReportByteLength > 0) { Byte[] outputReportBuffer = null; outputReportBuffer = new Byte[MyHid.Capabilities.OutputReportByteLength]; } // Flush any waiting reports in the input buffer. (optional) MyHid.FlushQueue( hidHandle ); } } } else { // The device wasn't detected. lstResults.Items.Add( "Device not found." ); cmdInputReportBufferSize.Enabled = false; cmdOnce.Enabled = true; Debug.WriteLine( " Device not found." ); ScrollToBottomOfListBox(); } return myDeviceDetected; } catch ( Exception ex ) { DisplayException( this.Name, ex ); throw ; } }
public LocalStorageDevice(string filename, bool enablePrivileges = false, bool useIoCompletionPort = false, bool unbuffered = false, bool deleteOnClose = false) { this.filename = filename; this.enablePrivileges = enablePrivileges; this.useIoCompletionPort = useIoCompletionPort; if (enablePrivileges) { Native32.EnableProcessPrivileges(); } Native32.GetDiskFreeSpace(filename.Substring(0, 3), out lpSectorsPerCluster, out lpBytesPerSector, out lpNumberOfFreeClusters, out lpTotalNumberOfClusters); uint fileAccess = Native32.GENERIC_READ | Native32.GENERIC_WRITE; uint fileShare = unchecked (((uint)FileShare.ReadWrite & ~(uint)FileShare.Inheritable)); uint fileCreation = unchecked ((uint)FileMode.OpenOrCreate); uint fileFlags = Native32.FILE_FLAG_OVERLAPPED; if (unbuffered) { fileFlags = fileFlags | Native32.FILE_FLAG_NO_BUFFERING; } if (deleteOnClose) { fileFlags = fileFlags | Native32.FILE_FLAG_DELETE_ON_CLOSE; } logHandle = Native32.CreateFileW(filename, fileAccess, fileShare, IntPtr.Zero, fileCreation, fileFlags, IntPtr.Zero); if (enablePrivileges) { Native32.EnableVolumePrivileges(ref filename, logHandle); } if (useIoCompletionPort) { ioCompletionPort = Native32.CreateIoCompletionPort( logHandle, IntPtr.Zero, (uint)logHandle.DangerousGetHandle().ToInt64(), 0); } try { ThreadPool.BindHandle(logHandle); } catch (Exception e) { Console.WriteLine("Log handle! : {0}", logHandle.ToString()); Console.WriteLine(e.ToString()); Environment.Exit(0); } }