当前位置: 首页>>代码示例>>C#>>正文


C# SafeFileHandle.Close方法代码示例

本文整理汇总了C#中SafeFileHandle.Close方法的典型用法代码示例。如果您正苦于以下问题:C# SafeFileHandle.Close方法的具体用法?C# SafeFileHandle.Close怎么用?C# SafeFileHandle.Close使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在SafeFileHandle的用法示例。


在下文中一共展示了SafeFileHandle.Close方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。

示例1: TryReadValue

        internal override bool TryReadValue(out long value)
        {
            try
            {
                IntPtr fileIntPtr = NativeMethods.CreateFileW(filename + ":" + Key, NativeConstants.GENERIC_READ, NativeConstants.FILE_SHARE_WRITE, IntPtr.Zero, NativeConstants.OPEN_ALWAYS, 0, IntPtr.Zero);
                if (fileIntPtr.ToInt32() <= 0)
                {
                    value = 0;
                    return false;
                }

                SafeFileHandle streamHandle = new SafeFileHandle(fileIntPtr, true);
                using (BinaryReader reader = new BinaryReader(new FileStream(streamHandle, FileAccess.Read)))
                {
                    value = reader.ReadInt64();
                }
                streamHandle.Close();

                return true;
            }
            catch
            {
                value = 0;
                return false;
            }
        }
开发者ID:bartwe,项目名称:Gearset,代码行数:26,代码来源:AdsValueStore.cs

示例2: DriveAccess

        public DriveAccess(string Path)
        {
            if (Path == null || Path.Length == 0)
                throw new ArgumentNullException("Path");

            driveHandle = CreateFile(Path, 0xC0000000, 0x03, IntPtr.Zero, 0x03, 0x80, IntPtr.Zero);
            if (driveHandle.IsInvalid)
            {
                driveHandle.Close();
                driveHandle.Dispose();
                driveHandle = null;
                throw new Exception("Win32 Exception : 0x" + Convert.ToString(Marshal.GetHRForLastWin32Error(), 16).PadLeft(8, '0'));
            }
            driveStream = new FileStream(driveHandle, FileAccess.ReadWrite);

            IntPtr p = Marshal.AllocHGlobal(24);
            uint returned;
            if (DeviceIoControl(driveHandle.DangerousGetHandle(), 0x00070000, IntPtr.Zero, 0, p, 40, out returned, IntPtr.Zero))
                unsafe { driveGeometry = new DriveGeometry((byte*)p.ToPointer()); }
            else
            {
                Marshal.FreeHGlobal(p);
                throw new Exception("Could not get the drive geometry information!");
            }
            Marshal.FreeHGlobal(p);
        }
开发者ID:zdimension,项目名称:SharpBoot,代码行数:26,代码来源:DriveAccess.cs

示例3: TryWriteValue

        internal override bool TryWriteValue(long value)
        {
            try
            {
                IntPtr fileIntPtr = NativeMethods.CreateFileW(filename + ":" + Key, NativeConstants.GENERIC_WRITE, NativeConstants.FILE_SHARE_WRITE, IntPtr.Zero, NativeConstants.OPEN_ALWAYS, 0, IntPtr.Zero);
                if (fileIntPtr.ToInt32() <= 0)
                    return false;

                SafeFileHandle streamHandle = new SafeFileHandle(fileIntPtr, true);
                using (BinaryWriter writer = new BinaryWriter(new FileStream(streamHandle, FileAccess.Write)))
                {
                    writer.Write(value);
                }
                streamHandle.Close();

                return true;
            }
            catch
            {
                return false;
            }
        }
开发者ID:bartwe,项目名称:Gearset,代码行数:22,代码来源:AdsValueStore.cs

示例4: GetSizeInternal

      internal static long GetSizeInternal(KernelTransaction transaction, SafeFileHandle safeHandle, string path, PathFormat pathFormat)
      {
         bool callerHandle = safeHandle != null;
         if (!callerHandle)
         {
            string pathLp = Path.GetExtendedLengthPathInternal(transaction, path, pathFormat, GetFullPathOptions.RemoveTrailingDirectorySeparator | GetFullPathOptions.FullCheck);

            safeHandle = CreateFileInternal(transaction, pathLp, ExtendedFileAttributes.None, null, FileMode.Open, FileSystemRights.ReadData, FileShare.Read, true, PathFormat.LongFullPath);
         }


         long fileSize;

         try
         {
            NativeMethods.GetFileSizeEx(safeHandle, out fileSize);
         }
         finally
         {
            // Handle is ours, dispose.
            if (!callerHandle && safeHandle != null)
               safeHandle.Close();
         }

         return fileSize;
      }
开发者ID:Sicos1977,项目名称:AlphaFS,代码行数:26,代码来源:File.GetSize.cs

示例5: FindTheHid

		///  <summary>
		///  Call HID functions that use Win32 API functions to locate a HID-class device
		///  by its Vendor ID and Product ID. Open a handle to the device.
		///  </summary>
		///          
		///  <returns>
		///   True if the device is detected, False if not detected.
		///  </returns>

		private Boolean FindTheHid()
		{
			var devicePathName = new String[128];
			String myDevicePathName = "";

			try
			{
				_deviceHandleObtained = false;
				CloseCommunications();

				//  Get the device's Vendor ID and Product ID from the form's text boxes.

				GetVendorAndProductIDsFromTextBoxes(ref _myVendorId, ref _myProductId);

				// Get the HID-class GUID.

				Guid hidGuid = _myHid.GetHidGuid();

				String 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.

				Boolean availableHids = _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 (availableHids)
				{
					Int32 memberIndex = 0;

					do
					{
						// Open the handle without read/write access to enable getting information about any HID, even system keyboards and mice.

						_hidHandle = _myHid.OpenHandle(devicePathName[memberIndex], false);

						functionName = "CreateFile";
						Debug.WriteLine(_myDebugging.ResultOfApiCall(functionName));
						Debug.WriteLine("  Returned handle: " + _hidHandle);

						if (!_hidHandle.IsInvalid)
						{
							// The returned handle is valid, 
							// so find out if this is the device we're looking for.

							_myHid.DeviceAttributes.Size = Marshal.SizeOf(_myHid.DeviceAttributes);

							Boolean success = _myHid.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));

								if ((_myHid.DeviceAttributes.VendorID == _myVendorId) && (_myHid.DeviceAttributes.ProductID == _myProductId))
								{
									Debug.WriteLine("  Handle obtained to my device");

									//  Display the information in form's list box.

									MyMarshalDataToForm(FormActions.AddItemToListBox, "Handle obtained to my device:");
									MyMarshalDataToForm(FormActions.AddItemToListBox, "  Vendor ID= " + Convert.ToString(_myHid.DeviceAttributes.VendorID, 16));
									MyMarshalDataToForm(FormActions.AddItemToListBox, "  Product ID = " + Convert.ToString(_myHid.DeviceAttributes.ProductID, 16));
									MyMarshalDataToForm(FormActions.ScrollToBottomOfListBox, "");

									_deviceHandleObtained = true;

									myDevicePathName = devicePathName[memberIndex];
								}
								else
								{
									//  It's not a match, so close the handle.

									_deviceHandleObtained = false;
									_hidHandle.Close();
								}
							}
							else
							{
								//  There was a problem retrieving the information.

								Debug.WriteLine("  Error in filling HIDD_ATTRIBUTES structure.");
								_deviceHandleObtained = false;
								_hidHandle.Close();
							}
//.........这里部分代码省略.........
开发者ID:TeamVader,项目名称:CANBUS_MONITOR,代码行数:101,代码来源:FrmMain.cs

示例6: Search_For_Wiimotes

        private void Search_For_Wiimotes()
        {
            // 1. Get the GUID of the HID class
            HIDImports2.HidD_GetHidGuid(out guid);

            // 2. get a handle to all devices that are part of the HID class
            IntPtr hDevInfo = HIDImports2.SetupDiGetClassDevs(ref guid, null, IntPtr.Zero, HIDImports2.DIGCF_DEVICEINTERFACE);// | HIDImports.DIGCF_PRESENT);

            // create a new interface data struct and initialize its size
            HIDImports2.SP_DEVICE_INTERFACE_DATA diData = new HIDImports2.SP_DEVICE_INTERFACE_DATA();
            diData.cbSize = Marshal.SizeOf(diData);

            // 3. get a device interface to a single device (enumerate all devices)
            while (HIDImports2.SetupDiEnumDeviceInterfaces(hDevInfo, IntPtr.Zero, ref guid, index, ref diData))
            {
                // create a detail struct and set its size
                HIDImports2.SP_DEVICE_INTERFACE_DETAIL_DATA diDetail = new HIDImports2.SP_DEVICE_INTERFACE_DETAIL_DATA();
                diDetail.cbSize = 5; //should be: (uint)Marshal.SizeOf(diDetail);, but that's the wrong size

                UInt32 size = 0;

                // get the buffer size for this device detail instance (returned in the size parameter)
                HIDImports2.SetupDiGetDeviceInterfaceDetail(hDevInfo, ref diData, IntPtr.Zero, 0, out size, IntPtr.Zero);

                // actually get the detail struct
                if (HIDImports2.SetupDiGetDeviceInterfaceDetail(hDevInfo, ref diData, ref diDetail, size, out size, IntPtr.Zero))
                {
                    // open a read/write handle to our device using the DevicePath returned
                    mHandle = HIDImports2.CreateFile(diDetail.DevicePath, FileAccess.ReadWrite, FileShare.ReadWrite, IntPtr.Zero, FileMode.Open, HIDImports2.EFileAttributes.Overlapped, IntPtr.Zero);

                    // 4. create an attributes struct and initialize the size
                    HIDImports2.HIDD_ATTRIBUTES attrib = new HIDImports2.HIDD_ATTRIBUTES();
                    attrib.Size = Marshal.SizeOf(attrib);

                    // get the attributes of the current device
                    if (HIDImports2.HidD_GetAttributes(mHandle.DangerousGetHandle(), ref attrib))
                    {
                        // if the vendor and product IDs match up
                        if ((attrib.VendorID == VID_old && attrib.ProductID == PID_old) || (attrib.VendorID == VID_new && attrib.ProductID == PID_new))
                        {
                            // 5. create a nice .NET FileStream wrapping the handle above
                            mStream = new FileStream(mHandle, FileAccess.ReadWrite, REPORT_LENGTH, true);
                            Console.WriteLine("Wii remote found");
                        }
                        else
                            mHandle.Close();
                    }
                }

                // move to the next device
                index++;
            }

            // 6. clean up our list
            HIDImports2.SetupDiDestroyDeviceInfoList(hDevInfo);
        }
开发者ID:danm0nster,项目名称:BACExperiment,代码行数:56,代码来源:FileHandler.cs

示例7: TryConnect

        public static bool TryConnect(ReportDevice device, Stream deviceStream, string devicePath, SafeFileHandle fileHandle)
        {
            bool success;
            try
            {
                device.Initialize();

                ((MsHidDeviceInfo)device.DeviceInfo).DevicePath = devicePath;
                SetDevicePathConnected(devicePath, true);
                success = true;
            }
            catch (TimeoutException)
            {
                device.Disconnect();
                deviceStream.Dispose();
                fileHandle.Close();
                success = false;
            }
            return success;
        }
开发者ID:nydehi,项目名称:wiidevicelibrary,代码行数:20,代码来源:MsHidDeviceProviderHelper.cs

示例8: Connect

        /// <summary>
        /// Connect to a Wiimote paired to the PC via Bluetooth
        /// </summary>
        public void Connect()
        {
            int index = 0;
            bool found = false;
            Guid guid;

            // get the GUID of the HID class
            HIDImports.HidD_GetHidGuid(out guid);

            // get a handle to all devices that are part of the HID class
            // Fun fact:  DIGCF_PRESENT worked on my machine just fine.  I reinstalled Vista, and now it no longer finds the Wiimote with that parameter enabled...
            IntPtr hDevInfo = HIDImports.SetupDiGetClassDevs(ref guid, null, IntPtr.Zero, HIDImports.DIGCF_DEVICEINTERFACE);// | HIDImports.DIGCF_PRESENT);

            // create a new interface data struct and initialize its size
            HIDImports.SP_DEVICE_INTERFACE_DATA diData = new HIDImports.SP_DEVICE_INTERFACE_DATA();
            diData.cbSize = Marshal.SizeOf(diData);

            // get a device interface to a single device (enumerate all devices)
            while(HIDImports.SetupDiEnumDeviceInterfaces(hDevInfo, IntPtr.Zero, ref guid, index, ref diData))
            {
                UInt32 size;

                // get the buffer size for this device detail instance (returned in the size parameter)
                HIDImports.SetupDiGetDeviceInterfaceDetail(hDevInfo, ref diData, IntPtr.Zero, 0, out size, IntPtr.Zero);

                // create a detail struct and set its size
                HIDImports.SP_DEVICE_INTERFACE_DETAIL_DATA diDetail = new HIDImports.SP_DEVICE_INTERFACE_DETAIL_DATA();

                // yeah, yeah...well, see, on Win x86, cbSize must be 5 for some reason.  On x64, apparently 8 is what it wants.
                // someday I should figure this out.  Thanks to Paul Miller on this...
                diDetail.cbSize = (uint)(IntPtr.Size == 8 ? 8 : 5);

                // actually get the detail struct
                if(HIDImports.SetupDiGetDeviceInterfaceDetail(hDevInfo, ref diData, ref diDetail, size, out size, IntPtr.Zero))
                {
                    Debug.WriteLine(index + " " + diDetail.DevicePath + " " + Marshal.GetLastWin32Error());

                    // open a read/write handle to our device using the DevicePath returned
                    mHandle = HIDImports.CreateFile(diDetail.DevicePath, FileAccess.ReadWrite, FileShare.ReadWrite, IntPtr.Zero, FileMode.Open, HIDImports.EFileAttributes.Overlapped, IntPtr.Zero);

                    // create an attributes struct and initialize the size
                    HIDImports.HIDD_ATTRIBUTES attrib = new HIDImports.HIDD_ATTRIBUTES();
                    attrib.Size = Marshal.SizeOf(attrib);

                    // get the attributes of the current device
                    if(HIDImports.HidD_GetAttributes(mHandle.DangerousGetHandle(), ref attrib))
                    {
                        // if the vendor and product IDs match up
                        if(attrib.VendorID == VID && attrib.ProductID == PID)
                        {
                            Debug.WriteLine("Found it!");
                            found = true;

                            // create a nice .NET FileStream wrapping the handle above
                            mStream = new FileStream(mHandle, FileAccess.ReadWrite, REPORT_LENGTH, true);

                            // start an async read operation on it
                            BeginAsyncRead();

                            // read the calibration info from the controller
                            try
                            {
                                ReadCalibration();
                            }
                            catch
                            {
                                // if we fail above, try the alternate HID writes
                                mAltWriteMethod = true;
                                ReadCalibration();
                            }

                            // force a status check to get the state of any extensions plugged in at startup
                            GetStatus();

                            break;
                        }
                        else
                        {
                            // otherwise this isn't the controller, so close up the file handle
                            mHandle.Close();
                        }
                    }
                }
                else
                {
                    // failed to get the detail struct
                    throw new WiimoteException("SetupDiGetDeviceInterfaceDetail failed on index " + index);
                }

                // move to the next device
                index++;
            }

            // clean up our list
            HIDImports.SetupDiDestroyDeviceInfoList(hDevInfo);

            // if we didn't find a Wiimote, throw an exception
//.........这里部分代码省略.........
开发者ID:pwner4once,项目名称:Airscribe,代码行数:101,代码来源:Wiimote.cs

示例9: FindWiimote

        internal static void FindWiimote(WiimoteFoundDelegate wiimoteFound)
        {
            int index = 0;
            bool found = false;
            Guid guid;
            SafeFileHandle mHandle;

            // get the GUID of the HID class
            HIDImports.HidD_GetHidGuid(out guid);

            // get a handle to all devices that are part of the HID class
            // Fun fact:  DIGCF_PRESENT worked on my machine just fine.  I reinstalled Vista, and now it no longer finds the Wiimote with that parameter enabled...
            IntPtr hDevInfo = HIDImports.SetupDiGetClassDevs(ref guid, null, IntPtr.Zero, HIDImports.DIGCF_DEVICEINTERFACE);// | HIDImports.DIGCF_PRESENT);

            // create a new interface data struct and initialize its size
            HIDImports.SP_DEVICE_INTERFACE_DATA diData = new HIDImports.SP_DEVICE_INTERFACE_DATA();
            diData.cbSize = Marshal.SizeOf(diData);

            // get a device interface to a single device (enumerate all devices)
            while(HIDImports.SetupDiEnumDeviceInterfaces(hDevInfo, IntPtr.Zero, ref guid, index, ref diData))
            {
                UInt32 size;

                // get the buffer size for this device detail instance (returned in the size parameter)
                HIDImports.SetupDiGetDeviceInterfaceDetail(hDevInfo, ref diData, IntPtr.Zero, 0, out size, IntPtr.Zero);

                // create a detail struct and set its size
                HIDImports.SP_DEVICE_INTERFACE_DETAIL_DATA diDetail = new HIDImports.SP_DEVICE_INTERFACE_DETAIL_DATA();

                // yeah, yeah...well, see, on Win x86, cbSize must be 5 for some reason.  On x64, apparently 8 is what it wants.
                // someday I should figure this out.  Thanks to Paul Miller on this...
                diDetail.cbSize = (uint)(IntPtr.Size == 8 ? 8 : 5);

                // actually get the detail struct
                if(HIDImports.SetupDiGetDeviceInterfaceDetail(hDevInfo, ref diData, ref diDetail, size, out size, IntPtr.Zero))
                {
                    Debug.WriteLine(string.Format("{0}: {1} - {2}", index, diDetail.DevicePath, Marshal.GetLastWin32Error()));

                    // open a read/write handle to our device using the DevicePath returned
                    mHandle = HIDImports.CreateFile(diDetail.DevicePath, FileAccess.ReadWrite, FileShare.ReadWrite, IntPtr.Zero, FileMode.Open, HIDImports.EFileAttributes.Overlapped, IntPtr.Zero);

                    // create an attributes struct and initialize the size
                    HIDImports.HIDD_ATTRIBUTES attrib = new HIDImports.HIDD_ATTRIBUTES();
                    attrib.Size = Marshal.SizeOf(attrib);

                    // get the attributes of the current device
                    if(HIDImports.HidD_GetAttributes(mHandle.DangerousGetHandle(), ref attrib))
                    {
                        // if the vendor and product IDs match up
                        if(attrib.VendorID == VID && attrib.ProductID == PID)
                        {
                            // it's a Wiimote
                            Debug.WriteLine("Found one!");
                            found = true;

                            // fire the callback function...if the callee doesn't care about more Wiimotes, break out
                            if(!wiimoteFound(diDetail.DevicePath))
                                break;
                        }
                    }
                    mHandle.Close();
                }
                else
                {
                    // failed to get the detail struct
                    throw new WiimoteException("SetupDiGetDeviceInterfaceDetail failed on index " + index);
                }

                // move to the next device
                index++;
            }

            // clean up our list
            HIDImports.SetupDiDestroyDeviceInfoList(hDevInfo);

            // if we didn't find a Wiimote, throw an exception
            if(!found)
                throw new WiimoteNotFoundException("No Wiimotes found in HID device list.");
        }
开发者ID:navhaxs,项目名称:wiimote-presenter-powerpoint,代码行数:79,代码来源:Wiimote.cs

示例10: Open

            /// <summary>
            /// Open the port specified by the Port property.
            /// </summary>
            public void Open()
            {
                if (IsDisposed) throw new ObjectDisposedException("NativeSerialPort");
                if (string.IsNullOrWhiteSpace(m_Port)) throw new InvalidOperationException("Port must first be set");
                if (IsOpen) throw new InvalidOperationException("Serial Port currently open");

                m_ComPortHandle = UnsafeNativeMethods.CreateFile(@"\\.\" + m_Port,
                    NativeMethods.FileAccess.GENERIC_READ | NativeMethods.FileAccess.GENERIC_WRITE,
                    NativeMethods.FileShare.FILE_SHARE_NONE,
                    IntPtr.Zero,
                    NativeMethods.CreationDisposition.OPEN_EXISTING,
                    NativeMethods.FileAttributes.FILE_FLAG_OVERLAPPED,
                    IntPtr.Zero);
                if (m_ComPortHandle.IsInvalid) WinIOError();

                NativeMethods.FileType t = UnsafeNativeMethods.GetFileType(m_ComPortHandle);
                if (t != NativeMethods.FileType.FILE_TYPE_CHAR && t != NativeMethods.FileType.FILE_TYPE_UNKNOWN) {
                    m_ComPortHandle.Close();
                    m_ComPortHandle = null;
                    throw new IOException("Wrong Filetype: " + m_Port);
                }

                // Set the default parameters
                UnsafeNativeMethods.SetupComm(m_ComPortHandle, m_DriverInQueue, m_DriverOutQueue);

                m_CommState = new CommState(m_ComPortHandle, m_CommState);
                m_CommProperties = new CommProperties(m_ComPortHandle);
                m_CommModem = new CommModemStatus(m_ComPortHandle);
                CommOverlappedIo commIo = new CommOverlappedIo(m_ComPortHandle, m_CommIo, Port);
                m_CommIo.Dispose();
                m_CommIo = commIo;
            }
开发者ID:DHMechatronicAG,项目名称:SerialPortStream,代码行数:35,代码来源:SerialPortStream.NativeSerialPort.cs

示例11: OpenWiimoteDeviceHandle

        private void OpenWiimoteDeviceHandle(string devicePath)
        {
            // open a read/write handle to our device using the DevicePath returned
            wiiHandle = HIDImports.CreateFile(devicePath, FileAccess.ReadWrite, FileShare.ReadWrite, IntPtr.Zero, FileMode.Open, HIDImports.EFileAttributes.Overlapped, IntPtr.Zero);

            // open a read/write handle to the PDA
            pdaHandle = HIDImports.CreateFile("\\\\.\\COM20", FileAccess.ReadWrite, FileShare.ReadWrite, IntPtr.Zero, FileMode.Open, HIDImports.EFileAttributes.Overlapped, IntPtr.Zero);

            // create an attributes struct and initialize the size
            HIDImports.HIDD_ATTRIBUTES attrib = new HIDImports.HIDD_ATTRIBUTES();
            attrib.Size = Marshal.SizeOf(attrib);

            // get the attributes of the current device
            if(HIDImports.HidD_GetAttributes(wiiHandle.DangerousGetHandle(), ref attrib))
            {
                // if the vendor and product IDs match up
                if(attrib.VendorID == VID && attrib.ProductID == PID)
                {
                    // create a nice .NET FileStream wrapping the handle above
                    wiiStream = new FileStream(wiiHandle, FileAccess.ReadWrite, REPORT_LENGTH, true);

                    // create a FileStream wrapping the pdaHandle
                    pdaStream = new FileStream(pdaHandle, FileAccess.ReadWrite, REPORT_LENGTH, true);

                    // Loop and wait for the PDA to write bytes
                    PDA_ReadWriteLoop();

                }
                else
                {
                    // otherwise this isn't the controller, so close up the file handle
                    wiiHandle.Close();
                    throw new WiimoteException("Attempted to open a non-Wiimote device.");
                }
            }
        }
开发者ID:hadleymj,项目名称:Senior-Design-Fall-2009,代码行数:36,代码来源:Wiimote.cs

示例12: FindEv3

		internal void FindEv3()
		{
			int index = 0;
			bool found = false;
			Guid guid;

			// get the GUID of the HID class
			HidImports.HidD_GetHidGuid(out guid);

			// get a handle to all devices that are part of the HID class
			IntPtr hDevInfo = HidImports.SetupDiGetClassDevs(ref guid, null, IntPtr.Zero, HidImports.DIGCF_DEVICEINTERFACE | HidImports.DIGCF_PRESENT);

			// create a new interface data struct and initialize its size
			HidImports.SP_DEVICE_INTERFACE_DATA diData = new HidImports.SP_DEVICE_INTERFACE_DATA();
			diData.cbSize = Marshal.SizeOf(diData);

			// get a device interface to a single device (enumerate all devices)
			while(HidImports.SetupDiEnumDeviceInterfaces(hDevInfo, IntPtr.Zero, ref guid, index, ref diData))
			{
				UInt32 size;

				// get the buffer size for this device detail instance (returned in the size parameter)
				HidImports.SetupDiGetDeviceInterfaceDetail(hDevInfo, ref diData, IntPtr.Zero, 0, out size, IntPtr.Zero);

				// create a detail struct and set its size
				HidImports.SP_DEVICE_INTERFACE_DETAIL_DATA diDetail = new HidImports.SP_DEVICE_INTERFACE_DETAIL_DATA();

				// yeah, yeah...well, see, on Win x86, cbSize must be 5 for some reason.  On x64, apparently 8 is what it wants.
				// someday I should figure this out.  Thanks to Paul Miller on this...
				diDetail.cbSize = (uint)(IntPtr.Size == 8 ? 8 : 5);

				// actually get the detail struct
				if(HidImports.SetupDiGetDeviceInterfaceDetail(hDevInfo, ref diData, ref diDetail, size, out size, IntPtr.Zero))
				{
					Debug.WriteLine("{0}: {1} - {2}", index, diDetail.DevicePath, Marshal.GetLastWin32Error());

					// open a read/write handle to our device using the DevicePath returned
					_handle = HidImports.CreateFile(diDetail.DevicePath, FileAccess.ReadWrite, FileShare.ReadWrite, IntPtr.Zero, FileMode.Open, HidImports.EFileAttributes.Overlapped, IntPtr.Zero);

					// create an attributes struct and initialize the size
					HidImports.HIDD_ATTRIBUTES attrib = new HidImports.HIDD_ATTRIBUTES();
					attrib.Size = Marshal.SizeOf(attrib);

					// get the attributes of the current device
					if(HidImports.HidD_GetAttributes(_handle.DangerousGetHandle(), ref attrib))
					{
						// if the vendor and product IDs match up
						if(attrib.VendorID == VID && attrib.ProductID == PID)
						{
							// it's a Ev3
							Debug.WriteLine("Found one!");
							found = true;

							IntPtr preparsedData;
							if(!HidImports.HidD_GetPreparsedData(_handle.DangerousGetHandle(), out preparsedData))
								throw new Exception("Could not get preparsed data for HID device");

							HidImports.HIDP_CAPS caps;
							if(HidImports.HidP_GetCaps(preparsedData, out caps) != HidImports.HIDP_STATUS_SUCCESS)
								throw new Exception("Could not get CAPS for HID device");

							HidImports.HidD_FreePreparsedData(ref preparsedData);

							_inputReport = new byte[caps.InputReportByteLength];
							_outputReport = new byte[caps.OutputReportByteLength];

							// create a nice .NET FileStream wrapping the handle above
							_stream = new FileStream(_handle, FileAccess.ReadWrite, _inputReport.Length, true);

							break;
						}

						_handle.Close();
					}
				}
				else
				{
					// failed to get the detail struct
					throw new Exception("SetupDiGetDeviceInterfaceDetail failed on index " + index);
				}

				// move to the next device
				index++;
			}

			// clean up our list
			HidImports.SetupDiDestroyDeviceInfoList(hDevInfo);

			// if we didn't find a EV3, throw an exception
			if(!found)
				throw new Exception("No LEGO EV3s found in HID device list.");
		}
开发者ID:BananaScheriff,项目名称:legoev3,代码行数:92,代码来源:UsbCommunication.cs

示例13: Read

        void Read(SafeFileHandle handle)
        {
            FileStream stream = new FileStream(handle, FileAccess.ReadWrite, (int)BUFFER_SIZE, true);
            byte[] buffer = new byte[BUFFER_SIZE];
            ASCIIEncoding encoder = new ASCIIEncoding();

            while (true)
            {
                int bytesRead = 0;

                try
                {
                    bytesRead = stream.Read(buffer, 0, (int)BUFFER_SIZE);
                }
                catch
                {
                    //read error has occurred
                    break;
                }

                //client has disconnected
                if (bytesRead == 0)
                    break;

                //fire message received event
                if (this.MessageReceived != null)
                    this.MessageReceived(encoder.GetString(buffer, 0, bytesRead));
            }

            handle.Close();
        }
开发者ID:pederjohnsen,项目名称:Nimbus,代码行数:31,代码来源:NexusPipe.cs

示例14: EnumerateFileIdBothDirectoryInfoInternal

      internal static IEnumerable<FileIdBothDirectoryInfo> EnumerateFileIdBothDirectoryInfoInternal(KernelTransaction transaction, SafeFileHandle safeHandle, string path, FileShare shareMode, bool continueOnException, PathFormat pathFormat)
      {
         if (!NativeMethods.IsAtLeastWindowsVista)
            throw new PlatformNotSupportedException(Resources.RequiresWindowsVistaOrHigher);

         bool callerHandle = safeHandle != null;
         if (!callerHandle)
         {
            if (Utils.IsNullOrWhiteSpace(path))
               throw new ArgumentNullException("path");

            string pathLp = Path.GetExtendedLengthPathInternal(transaction, path, pathFormat, GetFullPathOptions.RemoveTrailingDirectorySeparator | GetFullPathOptions.FullCheck);

            safeHandle = File.CreateFileInternal(transaction, pathLp, ExtendedFileAttributes.BackupSemantics, null, FileMode.Open, FileSystemRights.ReadData, shareMode, true, PathFormat.LongFullPath);
         }


         try
         {
            if (!NativeMethods.IsValidHandle(safeHandle, Marshal.GetLastWin32Error(), !continueOnException))
               yield break;

            // 2014-10-16: Number of returned items depends on the size of the buffer.
            // That does not seem right, investigate.
            using (var safeBuffer = new SafeGlobalMemoryBufferHandle(NativeMethods.DefaultFileBufferSize))
            {
               NativeMethods.IsValidHandle(safeBuffer, Marshal.GetLastWin32Error());

               long fileNameOffset = Marshal.OffsetOf(typeof(NativeMethods.FileIdBothDirInfo), "FileName").ToInt64();

               while (NativeMethods.GetFileInformationByHandleEx(safeHandle, NativeMethods.FileInfoByHandleClass.FileIdBothDirectoryInfo, safeBuffer.DangerousGetHandle(), NativeMethods.DefaultFileBufferSize))
               {
                  // CA2001:AvoidCallingProblematicMethods

                  IntPtr buffer = IntPtr.Zero;
                  bool successRef = false;
                  safeBuffer.DangerousAddRef(ref successRef);

                  // MSDN: The DangerousGetHandle method poses a security risk because it can return a handle that is not valid.
                  if (successRef)
                     buffer = safeBuffer.DangerousGetHandle();

                  safeBuffer.DangerousRelease();

                  if (buffer == IntPtr.Zero)
                     NativeError.ThrowException(Resources.HandleDangerousRef);

                  // CA2001:AvoidCallingProblematicMethods


                  while (buffer != IntPtr.Zero)
                  {
                     NativeMethods.FileIdBothDirInfo fibdi = Utils.MarshalPtrToStructure<NativeMethods.FileIdBothDirInfo>(0, buffer);

                     string fileName = Marshal.PtrToStringUni(new IntPtr(fileNameOffset + buffer.ToInt64()), (int)(fibdi.FileNameLength / 2));

                     if (!Utils.IsNullOrWhiteSpace(fileName) &&
                         !fileName.Equals(Path.CurrentDirectoryPrefix, StringComparison.OrdinalIgnoreCase) &&
                         !fileName.Equals(Path.ParentDirectoryPrefix, StringComparison.OrdinalIgnoreCase))
                        yield return new FileIdBothDirectoryInfo(fibdi, fileName);


                     buffer = fibdi.NextEntryOffset == 0
                        ? IntPtr.Zero
                        : new IntPtr(buffer.ToInt64() + fibdi.NextEntryOffset);
                  }
               }

               int lastError = Marshal.GetLastWin32Error();
               switch ((uint)lastError)
               {
                  case Win32Errors.ERROR_SUCCESS:
                  case Win32Errors.ERROR_NO_MORE_FILES:
                  case Win32Errors.ERROR_HANDLE_EOF:
                     yield break;

                  default:
                     NativeError.ThrowException(lastError, path);
                     break;
               }
            }
         }
         finally
         {
            // Handle is ours, dispose.
            if (!callerHandle && safeHandle != null)
               safeHandle.Close();
         }
      }
开发者ID:Sicos1977,项目名称:AlphaFS,代码行数:89,代码来源:Directory.EnumerateFileIdBothDirectoryInfo.cs

示例15: Init

        internal void Init(String path, FileMode mode, FileAccess access, int rights, bool useRights, FileShare share, int bufferSize, FileOptions options, Win32Native.SECURITY_ATTRIBUTES secAttrs, String msgPath, bool bFromProxy, bool useLongPath)
        { 
            if (path == null) 
                throw new ArgumentNullException("path", Environment.GetResourceString("ArgumentNull_Path"));
            if (path.Length == 0) 
                throw new ArgumentException(Environment.GetResourceString("Argument_EmptyPath"));
            Contract.EndContractBlock();

#if !FEATURE_PAL && FEATURE_MACL 
            FileSystemRights fileSystemRights = (FileSystemRights)rights;
#endif 
            // msgPath must be safe to hand back to untrusted code. 

            _fileName = msgPath;  // To handle odd cases of finalizing partially constructed objects. 
            _exposedHandle = false;

#if FEATURE_PAL
            Contract.Assert(!useRights, "Specifying FileSystemRights is not supported on this platform!"); 
#endif
 
            // don't include inheritable in our bounds check for share 
            FileShare tempshare = share & ~FileShare.Inheritable;
            String badArg = null; 

            if (mode < FileMode.CreateNew || mode > FileMode.Append)
                badArg = "mode";
            else if (!useRights && (access < FileAccess.Read || access > FileAccess.ReadWrite)) 
                badArg = "access";
#if !FEATURE_PAL && FEATURE_MACL 
            else if (useRights && (fileSystemRights < FileSystemRights.ReadData || fileSystemRights > FileSystemRights.FullControl)) 
                badArg = "rights";
#endif 
            else if (tempshare < FileShare.None || tempshare > (FileShare.ReadWrite | FileShare.Delete))
                badArg = "share";

            if (badArg != null) 
                throw new ArgumentOutOfRangeException(badArg, Environment.GetResourceString("ArgumentOutOfRange_Enum"));
 
            // NOTE: any change to FileOptions enum needs to be matched here in the error validation 
            if (options != FileOptions.None && (options & ~(FileOptions.WriteThrough | FileOptions.Asynchronous | FileOptions.RandomAccess | FileOptions.DeleteOnClose | FileOptions.SequentialScan | FileOptions.Encrypted | (FileOptions)0x20000000 /* NoBuffering */)) != 0)
                throw new ArgumentOutOfRangeException("options", Environment.GetResourceString("ArgumentOutOfRange_Enum")); 

            if (bufferSize <= 0)
                throw new ArgumentOutOfRangeException("bufferSize", Environment.GetResourceString("ArgumentOutOfRange_NeedPosNum"));
 
            // Write access validation
#if !FEATURE_PAL && FEATURE_MACL 
            if ((!useRights && (access & FileAccess.Write) == 0) 
                || (useRights && (fileSystemRights & FileSystemRights.Write) == 0))
#else 
            if (!useRights && (access & FileAccess.Write) == 0)
#endif //!FEATURE_PAL && FEATURE_MACL
            {
                if (mode==FileMode.Truncate || mode==FileMode.CreateNew || mode==FileMode.Create || mode==FileMode.Append) { 
                    // No write access
                    if (!useRights) 
                        throw new ArgumentException(Environment.GetResourceString("Argument_InvalidFileMode&AccessCombo", mode, access)); 
#if !FEATURE_PAL && FEATURE_MACL
                    else 
                        throw new ArgumentException(Environment.GetResourceString("Argument_InvalidFileMode&RightsCombo", mode, fileSystemRights));
#endif //!FEATURE_PAL && FEATURE_MACL
                }
            } 

#if !FEATURE_PAL && FEATURE_MACL 
            // FileMode.Truncate only works with GENERIC_WRITE (FileAccess.Write), source:MSDN 
            // For backcomp use FileAccess.Write when FileSystemRights.Write is specified
            if (useRights && (mode == FileMode.Truncate)) { 
                if (fileSystemRights == FileSystemRights.Write) {
                    useRights = false;
                    access = FileAccess.Write;
                } 
                else {
                    throw new ArgumentException(Environment.GetResourceString("Argument_InvalidFileModeTruncate&RightsCombo", mode, fileSystemRights)); 
                } 
            }
#endif 

            int fAccess;
            if (!useRights) {
                fAccess = access == FileAccess.Read? GENERIC_READ: 
                access == FileAccess.Write? GENERIC_WRITE:
                GENERIC_READ | GENERIC_WRITE; 
            } 
            else {
                fAccess = rights; 
            }

            // Get absolute path - Security needs this to prevent something
            // like trying to create a file in c:\tmp with the name 
            // "..\WinNT\System32\ntoskrnl.exe".  Store it for user convenience.
            int maxPath = useLongPath ? Path.MaxLongPath : Path.MaxPath; 
            String filePath = Path.NormalizePath(path, true, maxPath); 

            _fileName = filePath; 

            // Prevent access to your disk drives as raw block devices.
            if (filePath.StartsWith("\\\\.\\", StringComparison.Ordinal))
                throw new ArgumentException(Environment.GetResourceString("Arg_DevicesNotSupported")); 

//.........这里部分代码省略.........
开发者ID:sjyanxin,项目名称:WPFSource,代码行数:101,代码来源:FileStream.cs


注:本文中的SafeFileHandle.Close方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。