• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

C# SafeFileHandle类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了C#中SafeFileHandle的典型用法代码示例。如果您正苦于以下问题:C# SafeFileHandle类的具体用法?C# SafeFileHandle怎么用?C# SafeFileHandle使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。



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

示例1: GetAttributes

		/// <summary>
		/// Get HID attributes.
		/// </summary>
		/// <param name="hidHandle"> HID handle retrieved with CreateFile </param>
		/// <param name="deviceAttributes"> HID attributes structure </param>
		/// <returns> true on success </returns>

		internal Boolean GetAttributes(SafeFileHandle hidHandle, ref NativeMethods.HIDD_ATTRIBUTES deviceAttributes)
		{
			Boolean success;
			try
			{
				//  ***
				//  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 = NativeMethods.HidD_GetAttributes(hidHandle, ref deviceAttributes);
			}

			catch (Exception ex)
			{
				DisplayException(ModuleName, ex);
				throw;
			}
			return success;
		}
开发者ID:glocklueng,项目名称:stm32f4_HID_Aplication,代码行数:38,代码来源:Hid.cs


示例2: ReadFileNative

 private static unsafe int ReadFileNative(SafeFileHandle hFile, byte[] bytes, int offset, int count, int mustBeZero, out int errorCode)
 {
     int num;
     int num2;
     if ((bytes.Length - offset) < count)
     {
         throw new IndexOutOfRangeException(Environment.GetResourceString("IndexOutOfRange_IORaceCondition"));
     }
     if (bytes.Length == 0)
     {
         errorCode = 0;
         return 0;
     }
     WaitForAvailableConsoleInput(hFile);
     fixed (byte* numRef = bytes)
     {
         num = ReadFile(hFile, numRef + offset, count, out num2, Win32Native.NULL);
     }
     if (num == 0)
     {
         errorCode = Marshal.GetLastWin32Error();
         if (errorCode == 0x6d)
         {
             return 0;
         }
         return -1;
     }
     errorCode = 0;
     return num2;
 }
开发者ID:pritesh-mandowara-sp,项目名称:DecompliedDotNetLibraries,代码行数:30,代码来源:__ConsoleStream.cs


示例3: Poll

        /// <summary>
        /// Polls a File Descriptor for the passed in flags.
        /// </summary>
        /// <param name="fd">The descriptor to poll</param>
        /// <param name="events">The events to poll for</param>
        /// <param name="timeout">The amount of time to wait; -1 for infinite, 0 for immediate return, and a positive number is the number of milliseconds</param>
        /// <param name="triggered">The events that were returned by the poll call. May be PollEvents.POLLNONE in the case of a timeout.</param>
        /// <returns>An error or Error.SUCCESS.</returns>
        internal static unsafe Error Poll(SafeFileHandle fd, PollEvents events, int timeout, out PollEvents triggered)
        {
            bool gotRef = false;
            try
            {
                fd.DangerousAddRef(ref gotRef);

                var pollEvent = new PollEvent
                {
                    FileDescriptor = fd.DangerousGetHandle().ToInt32(),
                    Events = events,
                };

                uint unused;
                Error err = Poll(&pollEvent, 1, timeout, &unused);
                triggered = pollEvent.TriggeredEvents;
                return err;
            }
            finally
            {
                if (gotRef)
                {
                    fd.DangerousRelease();
                }
            }
        }
开发者ID:er0dr1guez,项目名称:corefx,代码行数:34,代码来源:Interop.Poll.cs


示例4: Initialize

 public bool Initialize()
 {
     if (!AttachConsole(ATTACH_PARENT_PROCESS)) AllocConsole();
     if (GetConsoleWindow() == IntPtr.Zero)
     {
         FreeConsole();
         return false;
     }
     oldOutput = Console.Out;
     oldEncoding = Console.OutputEncoding;
     var encoding = new UTF8Encoding(false);
     SetConsoleOutputCP((uint)encoding.CodePage);
     Console.OutputEncoding = encoding;
     Stream outStream;
     try
     {
         var safeFileHandle = new SafeFileHandle(GetStdHandle(STD_OUTPUT_HANDLE), true);
         outStream = new FileStream(safeFileHandle, FileAccess.Write);
     }
     catch (Exception)
     {
         outStream = Console.OpenStandardOutput();
     }
     Console.SetOut(new StreamWriter(outStream, encoding) { AutoFlush = true });
     return true;
 }
开发者ID:AEtherSurfer,项目名称:Oxide,代码行数:26,代码来源:ConsoleWindow.cs


示例5: CreateFileMapping

 internal static extern SafeMemoryMappedFileHandle CreateFileMapping(
     SafeFileHandle hFile,
     ref SECURITY_ATTRIBUTES lpFileMappingAttributes,
     int flProtect,
     int dwMaximumSizeHigh,
     int dwMaximumSizeLow,
     string lpName);
开发者ID:noahfalk,项目名称:corefx,代码行数:7,代码来源:Interop.CreateFileMapping.cs


示例6: CreateTempFile

        /// <summary>
        /// Creates a file stream with the given filename that is deleted when either the
        /// stream is closed, or the application is terminated.
        /// </summary>
        /// <remarks>
        /// If the file already exists, it is overwritten without any error (CREATE_ALWAYS).
        /// </remarks>
        /// <param name="fileName">The full path to the file to create.</param>
        /// <returns>A Stream with read and write access.</returns>
        public static FileStream CreateTempFile(string fileName)
        {
            FileStream stream;
            IntPtr hFile = SafeNativeMethods.CreateFileW(
                fileName,
                NativeConstants.GENERIC_READ | NativeConstants.GENERIC_WRITE,
                NativeConstants.FILE_SHARE_READ,
                IntPtr.Zero,
                NativeConstants.CREATE_ALWAYS,
                NativeConstants.FILE_ATTRIBUTE_TEMPORARY |
                    NativeConstants.FILE_FLAG_DELETE_ON_CLOSE |
                    NativeConstants.FILE_ATTRIBUTE_NOT_CONTENT_INDEXED,
                IntPtr.Zero);

            if (hFile == NativeConstants.INVALID_HANDLE_VALUE)
            {
                NativeMethods.ThrowOnWin32Error("CreateFileW returned INVALID_HANDLE_VALUE");
            }

            SafeFileHandle sfhFile = new SafeFileHandle(hFile, true);
            try
            {
                stream = new FileStream(sfhFile, FileAccess.ReadWrite);
            }

            catch (Exception)
            {
                SafeNativeMethods.CloseHandle(hFile);
                hFile = IntPtr.Zero;
                throw;
            }

            return stream;
        }
开发者ID:nkaligin,项目名称:paint-mono,代码行数:43,代码来源:FileSystem.cs


示例7: SerialPortFixer

        private SerialPortFixer(string portName)
        {
            const int dwFlagsAndAttributes = 0x40000000;
            const int dwAccess = unchecked((int)0xC0000000);

            if (string.IsNullOrEmpty(portName))
            {
                throw new ArgumentException("Invalid Serial Port", "portName");
            }
            SafeFileHandle hFile = NativeMethods.CreateFile(@"\\.\" + portName, dwAccess, 0, IntPtr.Zero, 3, dwFlagsAndAttributes,
                                              IntPtr.Zero);
            if (hFile.IsInvalid)
            {
                WinIoError();
            }
            try
            {
                int fileType = NativeMethods.GetFileType(hFile);
                if ((fileType != 2) && (fileType != 0))
                {
                    throw new ArgumentException("Invalid Serial Port", "portName");
                }
                m_Handle = hFile;
                InitializeDcb();
            }
            catch
            {
                hFile.Close();
                m_Handle = null;
                throw;
            }
        }
开发者ID:sambengtson,项目名称:netPyramid-RS-232,代码行数:32,代码来源:SerialPortFixer.cs


示例8: 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


示例9: FilterConnectCommunicationPort

 static extern uint FilterConnectCommunicationPort(
     string lpPortName,           // LPCWSTR lpPortName,
     uint dwOptions,              // DWORD dwOptions,
     IntPtr lpContext,            // LPCVOID lpContext,
     uint dwSizeOfContext,        // WORD dwSizeOfContext
     IntPtr lpSecurityAttributes, // LP_SECURITY_ATTRIBUTES lpSecurityAttributes
     out SafeFileHandle hPort);  // HANDLE *hPort
开发者ID:ioan-stefanovici,项目名称:Moirai,代码行数:7,代码来源:IoFlowRuntime.cs


示例10: Open

        /* open hid device */
        public bool Open(HIDInfo dev)
        {
            /* safe file handle */
            SafeFileHandle shandle;

            /* opens hid device file */
            handle = Native.CreateFile(dev.Path,
                Native.GENERIC_READ | Native.GENERIC_WRITE,
                Native.FILE_SHARE_READ | Native.FILE_SHARE_WRITE,
                IntPtr.Zero, Native.OPEN_EXISTING, Native.FILE_FLAG_OVERLAPPED,
                IntPtr.Zero);

            /* whops */
            if (handle == Native.INVALID_HANDLE_VALUE) {
                return false;
            }

            /* build up safe file handle */
            shandle = new SafeFileHandle(handle, false);

            /* prepare stream - async */
            _fileStream = new FileStream(shandle, FileAccess.ReadWrite,
                32, true);

            /* report status */
            return true;
        }
开发者ID:sky8273,项目名称:MightyHID,代码行数:28,代码来源:HIDDev.cs


示例11: FlushQueue

		///  <summary>
		///  Remove any Input reports waiting in the buffer.
		///  </summary>
		///  <param name="hidHandle"> a handle to a device.   </param>
		///  <returns>
		///  True on success, False on failure.
		///  </returns>

		internal Boolean FlushQueue(SafeFileHandle hidHandle)
		{
			try
			{
				//  ***
				//  API function: HidD_FlushQueue

				//  Purpose: Removes any Input reports waiting in the buffer.

				//  Accepts: a handle to the device.

				//  Returns: True on success, False on failure.
				//  ***

				Boolean success = NativeMethods.HidD_FlushQueue(hidHandle);

				return success;
			}

			catch (Exception ex)
			{
				DisplayException(ModuleName, ex);
				throw;
			}
		}
开发者ID:TeamVader,项目名称:CANBUS_MONITOR,代码行数:33,代码来源:Hid.cs


示例12: __ConsoleStream

 internal __ConsoleStream(SafeFileHandle handle, FileAccess access)
 { 
     Contract.Assert(handle != null && !handle.IsInvalid, "__ConsoleStream expects a valid handle!");
     _handle = handle; 
     _canRead = access == FileAccess.Read; 
     _canWrite = access == FileAccess.Write;
 } 
开发者ID:sjyanxin,项目名称:WPFSource,代码行数:7,代码来源:__ConsoleStream.cs


示例13: CreateFileMapping

 public static IntPtr CreateFileMapping(SafeFileHandle handle,
     FileMapProtection flProtect, long ddMaxSize, string lpName)
 {
     var Hi = (int) (ddMaxSize/int.MaxValue);
     var Lo = (int) (ddMaxSize%int.MaxValue);
     return CreateFileMapping(handle.DangerousGetHandle(), IntPtr.Zero, flProtect, Hi, Lo, lpName);
 }
开发者ID:huoxudong125,项目名称:HQF.Tutorial.MMF,代码行数:7,代码来源:Win32API.cs


示例14: Device

 // Methods
 public Device(string path)
 {
     IntPtr ptr;
     this.Handle = GetDeviceHandle(path);
     this.Attributes = new Hid.HIDD_ATTRIBUTES();
     Hid.HidD_GetAttributes(this.Handle, ref this.Attributes);
     if (Marshal.GetLastWin32Error() != 0)
     {
         throw new Win32Exception("Cannot get device attributes.");
     }
     this.Capabilities = new Hid.HIDP_CAPS();
     if (Hid.HidD_GetPreparsedData(this.Handle, out ptr))
     {
         try
         {
             Hid.HidP_GetCaps(ptr, out this.Capabilities);
         }
         finally
         {
             Hid.HidD_FreePreparsedData(ref ptr);
         }
     }
     if (Marshal.GetLastWin32Error() != 0)
     {
         throw new Win32Exception("Cannot get device capabilities.");
     }
     SafeFileHandle handle = new SafeFileHandle(this.Handle, true);
     this.DataStream = new FileStream(handle, FileAccess.ReadWrite, this.Capabilities.InputReportByteLength, true);
     timeout = 3000;
 }
开发者ID:BackupTheBerlios,项目名称:aladdin-svn,代码行数:31,代码来源:Device.cs


示例15: RunTest

    int RunTest()
    {
        try
        {
            try
            {
                using (SafeFileHandle sfh = new SafeFileHandle(CreateFile("test.txt", 0x40000000, 0, 0, 2, 0x80, 0), true))
                {

                    ThreadPool.BindHandle(sfh);
                }
            }
            catch (Exception ex)
            {
                if (ex.ToString().IndexOf("0x80070057") != -1) // E_INVALIDARG, the handle isn't overlapped
                {
                    Console.WriteLine("Test passed");
                    return (100);
                }
                else
                {
                    Console.WriteLine("Got wrong error: {0}", ex);
                }
            }
        }
        finally
        {
            if (File.Exists("test.txt"))
            {
                File.Delete("test.txt");
            }
        }
        Console.WriteLine("Didn't get argument null exception");
        return (99);
    }
开发者ID:CheneyWu,项目名称:coreclr,代码行数:35,代码来源:bindhandleinvalid3.cs


示例16: ImageOverFilter

        public ImageOverFilter()
            : base("CSharp Image Overlay Filter")
        {
            vid.DSplugin = true;



            NativeMethods.AllocConsole();
            IntPtr stdHandle = NativeMethods.GetStdHandle(STD_OUTPUT_HANDLE);
            SafeFileHandle safeFileHandle = new SafeFileHandle(stdHandle, true);
            FileStream fileStream = new FileStream(safeFileHandle, FileAccess.Write);
            Encoding encoding = System.Text.Encoding.GetEncoding(MY_CODE_PAGE);
            StreamWriter standardOutput = new StreamWriter(fileStream, encoding);
            standardOutput.AutoFlush = true;
            Console.SetOut(standardOutput);
            Console.WriteLine("This text you can see in console window.");

            AMMediaType pmt = new AMMediaType() { majorType = MediaType.Video, subType = MediaSubType.YUY2, formatType = MediaType.Video, formatPtr = IntPtr.Zero };
            SetMediaType(PinDirection.Input, pmt);
            pmt.Free();
            
            pmt = new AMMediaType() { majorType = MediaType.Video, subType = MediaSubType.RGB24, formatType = MediaType.Video, formatPtr = IntPtr.Zero };
            SetMediaType(PinDirection.Output, pmt);
            pmt.Free();
        }
开发者ID:CraigElder,项目名称:MissionPlanner,代码行数:25,代码来源:ImageOverFilter.cs


示例17: PrintScoresMatrix

 public void PrintScoresMatrix(SafeFileHandle handle)
     {
     if (this.nativeDesignScorer != IntPtr.Zero)
         {
         NadirHelper.PrintScoresMatrix(this.nativeDesignScorer, handle.DangerousGetHandle());
         }
     }
开发者ID:rgatkinson,项目名称:nadir,代码行数:7,代码来源:Output.cs


示例18: ReadFile

 public static extern bool ReadFile(
   SafeFileHandle hFile,
   IntPtr pBuffer,
   int numberOfBytesToRead,
   int[] pNumberOfBytesRead,
   NativeOverlapped[] lpOverlapped // should be fixed, if not null
   );
开发者ID:mbbill,项目名称:vs-chromium,代码行数:7,代码来源:NativeMethods.cs


示例19: ReadFile

		public static extern bool ReadFile(
			SafeFileHandle hFile,
			byte* pBuffer,
			int numBytesToRead,
			out int pNumberOfBytesRead,
			NativeOverlapped* lpOverlapped
			);
开发者ID:kijanawoodard,项目名称:ravendb,代码行数:7,代码来源:NativeMethods.cs


示例20: SerialPortFixer

		private SerialPortFixer(string portName)
		{
			if (portName == null || !portName.StartsWith("COM", StringComparison.OrdinalIgnoreCase))
			{
				throw new ArgumentException("Invalid Serial Port", "portName");
			}
			else
			{
				SafeFileHandle safeFileHandle = SerialPortFixer.CreateFile(string.Concat("\\\\.\\", portName), -1073741824, 0, IntPtr.Zero, 3, 1073741824, IntPtr.Zero);
				if (safeFileHandle.IsInvalid)
				{
					SerialPortFixer.WinIoError();
				}
				try
				{
					int fileType = SerialPortFixer.GetFileType(safeFileHandle);
					if (fileType == 2 || fileType == 0)
					{
						this.m_Handle = safeFileHandle;
						this.InitializeDcb();
					}
					else
					{
						throw new ArgumentException("Invalid Serial Port", "portName");
					}
				}
				catch
				{
					safeFileHandle.Close();
					this.m_Handle = null;
					throw;
				}
				return;
			}
		}
开发者ID:gbmakaveli,项目名称:GSMComm,代码行数:35,代码来源:SerialPortFixer.cs



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


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
C# SafeFreeCredentials类代码示例发布时间:2022-05-24
下一篇:
C# SafeDictionary类代码示例发布时间:2022-05-24
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap