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


C# SafeFileHandle.Dispose方法代码示例

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


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

示例1: Open

        /// <summary>Opens the specified file with the requested flags and mode.</summary>
        /// <param name="path">The path to the file.</param>
        /// <param name="flags">The flags with which to open the file.</param>
        /// <param name="mode">The mode for opening the file.</param>
        /// <returns>A SafeFileHandle for the opened file.</returns>
        internal static SafeFileHandle Open(string path, Interop.Sys.OpenFlags flags, int mode)
        {
            Debug.Assert(path != null);

            SafeFileHandle handle = new SafeFileHandle(ownsHandle: true);

            // If we fail to open the file due to a path not existing, we need to know whether to blame
            // the file itself or its directory.  If we're creating the file, then we blame the directory,
            // otherwise we blame the file.
            bool enoentDueToDirectory = (flags & Interop.Sys.OpenFlags.O_CREAT) != 0;

            // Open the file. 
            int fd;
            while (Interop.CheckIo(fd = Interop.Sys.Open(path, flags, mode), path, isDirectory: enoentDueToDirectory,
                errorRewriter: e => (e.Error == Interop.Error.EISDIR) ? Interop.Error.EACCES.Info() : e)) ;
            handle.SetHandle(fd);

            // Make sure it's not a directory; we do this after opening it once we have a file descriptor 
            // to avoid race conditions.
            Interop.Sys.FileStatus status;
            if (Interop.Sys.FStat(fd, out status) != 0)
            {
                handle.Dispose();
                throw Interop.GetExceptionForIoErrno(Interop.Sys.GetLastErrorInfo(), path);
            }
            if ((status.Mode & Interop.Sys.FileTypes.S_IFMT) == Interop.Sys.FileTypes.S_IFDIR)
            {
                handle.Dispose();
                throw Interop.GetExceptionForIoErrno(Interop.Error.EACCES.Info(), path, isDirectory: true);
            }

            return handle;
        }
开发者ID:nnyamhon,项目名称:corefx,代码行数:38,代码来源:SafeFileHandle.Unix.cs

示例2: Open

        /// <summary>Opens the specified file with the requested flags and mode.</summary>
        /// <param name="path">The path to the file.</param>
        /// <param name="flags">The flags with which to open the file.</param>
        /// <param name="mode">The mode for opening the file.</param>
        /// <returns>A SafeFileHandle for the opened file.</returns>
        internal static SafeFileHandle Open(string path, Interop.Sys.OpenFlags flags, int mode)
        {
            Debug.Assert(path != null);

            // SafeFileHandle wraps a file descriptor rather than a pointer, and a file descriptor is always 4 bytes
            // rather than being pointer sized, which means we can't utilize the runtime's ability to marshal safe handles.
            // Ideally this would be a constrained execution region, but we don't have access to PrepareConstrainedRegions.
            // We still use a finally block to house the code that opens the file and stores the handle in hopes
            // of making it as non-interruptable as possible.  The SafeFileHandle is also allocated first to avoid
            // the allocation after getting the file descriptor but before storing it.
            SafeFileHandle handle = new SafeFileHandle(ownsHandle: true);
            try { } finally
            {
                // If we fail to open the file due to a path not existing, we need to know whether to blame
                // the file itself or its directory.  If we're creating the file, then we blame the directory,
                // otherwise we blame the file.
                bool enoentDueToDirectory = (flags & Interop.Sys.OpenFlags.O_CREAT) != 0;

                // Open the file.
                int fd;
                while (Interop.CheckIo(fd = Interop.Sys.Open(path, flags, mode), path, isDirectory: enoentDueToDirectory,
                    errorRewriter: e => (e.Error == Interop.Error.EISDIR) ? Interop.Error.EACCES.Info() : e)) ;
                Debug.Assert(fd >= 0);
                handle.SetHandle((IntPtr)fd);
                Debug.Assert(!handle.IsInvalid);

                // Make sure it's not a directory; we do this after opening it once we have a file descriptor 
                // to avoid race conditions.
                Interop.Sys.FileStatus status;
                if (Interop.Sys.FStat(fd, out status) != 0)
                {
                    handle.Dispose();
                    throw Interop.GetExceptionForIoErrno(Interop.Sys.GetLastErrorInfo(), path);
                }
                if ((status.Mode & Interop.Sys.FileTypes.S_IFMT) == Interop.Sys.FileTypes.S_IFDIR)
                {
                    handle.Dispose();
                    throw Interop.GetExceptionForIoErrno(Interop.Error.EACCES.Info(), path, isDirectory: true);
                }
            }
            return handle;
        }
开发者ID:nblumhardt,项目名称:corefx,代码行数:47,代码来源:SafeFileHandle.Unix.cs

示例3: CreateSharedBackingObject

        private static FileStream CreateSharedBackingObject(
            Interop.libc.MemoryMappedProtections protections, long capacity)
        {
            // The POSIX shared memory object name must begin with '/'.  After that we just want something short and unique.
            string mapName = "/corefx_map_" + Guid.NewGuid().ToString("N");

            // Determine the flags to use when creating the shared memory object
            Interop.Sys.OpenFlags flags = (protections & Interop.libc.MemoryMappedProtections.PROT_WRITE) != 0 ?
                Interop.Sys.OpenFlags.O_RDWR :
                Interop.Sys.OpenFlags.O_RDONLY;
            flags |= Interop.Sys.OpenFlags.O_CREAT | Interop.Sys.OpenFlags.O_EXCL; // CreateNew

            // Determine the permissions with which to create the file
            Interop.Sys.Permissions perms = default(Interop.Sys.Permissions);
            if ((protections & Interop.libc.MemoryMappedProtections.PROT_READ) != 0)
                perms |= Interop.Sys.Permissions.S_IRUSR;
            if ((protections & Interop.libc.MemoryMappedProtections.PROT_WRITE) != 0)
                perms |= Interop.Sys.Permissions.S_IWUSR;
            if ((protections & Interop.libc.MemoryMappedProtections.PROT_EXEC) != 0)
                perms |= Interop.Sys.Permissions.S_IXUSR;

            // Create the shared memory object.
            int fd;
            Interop.CheckIo(fd = Interop.Sys.ShmOpen(mapName, flags, (int)perms), mapName);
            SafeFileHandle fileHandle = new SafeFileHandle((IntPtr)fd, ownsHandle: true);
            try
            {
                // Unlink the shared memory object immediatley so that it'll go away once all handles 
                // to it are closed (as with opened then unlinked files, it'll remain usable via
                // the open handles even though it's unlinked and can't be opened anew via its name).
                Interop.CheckIo(Interop.Sys.ShmUnlink(mapName));

                // Give it the right capacity.  We do this directly with ftruncate rather
                // than via FileStream.SetLength after the FileStream is created because, on some systems,
                // lseek fails on shared memory objects, causing the FileStream to think it's unseekable,
                // causing it to preemptively throw from SetLength.
                Interop.CheckIo(Interop.libc.ftruncate(fd, capacity));

                // Wrap the file descriptor in a stream and return it.
                return new FileStream(fileHandle, TranslateProtectionsToFileAccess(protections));
            }
            catch
            {
                fileHandle.Dispose();
                throw;
            }
        }
开发者ID:raggiskula,项目名称:corefx,代码行数:47,代码来源:MemoryMappedFile.Unix.BackingObject_Memory.cs

示例4: Open

        public void Open()
        {
            try
              {
            _deviceHandle = NativeInterface.CreateFile_SafeFileHandle(_devicePath,
              (NativeInterface.GENERIC_WRITE | NativeInterface.GENERIC_READ),
              NativeInterface.FILE_SHARE_READ | NativeInterface.FILE_SHARE_WRITE,
              IntPtr.Zero,
              NativeInterface.OPEN_EXISTING,
              NativeInterface.FILE_ATTRIBUTE_NORMAL | NativeInterface.FILE_FLAG_OVERLAPPED,
              0);
            if (_deviceHandle.IsInvalid)
            {
              throw new Win32Exception("Failed to open WinUSB device handle.");
            }

            _InitializeDevice();
              }
              catch (Exception)
              {
            if (_deviceHandle != null)
            {
              _deviceHandle.Dispose();
              _deviceHandle = null;
            }

            _FreeWinUSB();
            throw;
              }
        }
开发者ID:brandonlw,项目名称:vicar,代码行数:30,代码来源:WinUSBDevice.cs

示例5: OpenDevice

        public void OpenDevice(string devicePathName)
        {
            try
            {
                _deviceHandle = FileIO.CreateFile(devicePathName,
                        (FileIO.GENERIC_WRITE | FileIO.GENERIC_READ),
                        FileIO.FILE_SHARE_READ | FileIO.FILE_SHARE_WRITE,
                        IntPtr.Zero,
                        FileIO.OPEN_EXISTING,
                        FileIO.FILE_ATTRIBUTE_NORMAL | FileIO.FILE_FLAG_OVERLAPPED,
                        0);
                if (_deviceHandle.IsInvalid)
                    throw APIException.Win32("Failed to open WinUSB device handle.");
                InitializeDevice();

            }
            catch(Exception)
            {
                if (_deviceHandle != null)
                {
                    _deviceHandle.Dispose();
                    _deviceHandle = null;
                }
                FreeWinUSB();
                throw;
            }
        }
开发者ID:shangdawei,项目名称:winusb,代码行数:27,代码来源:WinUSBDevice.cs

示例6: USNHelper

        /// <summary>
        /// Constructs a new USN helper instance
        /// </summary>
        /// <param name="path">The path to the folder to perform USN services</param>
        /// <param name="volumeRoot">The root volume where the USN lookup is performed</param>
        internal USNHelper(string path, string volumeRoot)
        {
            if (Utility.Utility.IsClientLinux)
                throw new Exception(Strings.USNHelper.LinuxNotSupportedError);

            if (!System.IO.Path.IsPathRooted(path))
                throw new Exception(string.Format("Path {0} is not rooted", path));

            m_path = Utility.Utility.AppendDirSeparator(path);

            try
            {
                string devicename = @"\\.\" + System.IO.Path.GetPathRoot(path).TrimEnd('\\');
                if (volumeRoot != null)
                    volumeRoot = volumeRoot.TrimEnd('\\');

                m_volumeHandle = Win32USN.CreateFile(volumeRoot == null ? devicename : volumeRoot, Win32USN.EFileAccess.GenericRead, Win32USN.EFileShare.ReadWrite, IntPtr.Zero, Win32USN.ECreationDisposition.OpenExisting, Win32USN.EFileAttributes.BackupSemantics, IntPtr.Zero);
                if (m_volumeHandle == null || m_volumeHandle.IsInvalid)
                    throw new Win32Exception(Marshal.GetLastWin32Error());

                uint bytesReturned = 0;
                if (!Win32USN.DeviceIoControl(m_volumeHandle, Win32USN.EIOControlCode.FsctlQueryUsnJournal, null, 0, out m_journal, (uint)Marshal.SizeOf(typeof(Win32USN.USN_JOURNAL_DATA)), ref bytesReturned, IntPtr.Zero))
                    throw new Win32Exception(Marshal.GetLastWin32Error());

                Win32USN.BY_HANDLE_FILE_INFORMATION fileInfo;
                using (SafeFileHandle driveHandle = Win32USN.CreateFile(System.IO.Path.GetPathRoot(path), Win32USN.EFileAccess.GenericRead, Win32USN.EFileShare.ReadWrite, IntPtr.Zero, Win32USN.ECreationDisposition.OpenExisting, Win32USN.EFileAttributes.BackupSemantics, IntPtr.Zero))
                    if (!Win32USN.GetFileInformationByHandle(driveHandle, out fileInfo))
                        throw new Win32Exception(Marshal.GetLastWin32Error());

                m_volumeRootFileNameReferenceNumber = ((ulong)fileInfo.FileIndexHigh << 32) | ((ulong)fileInfo.FileIndexLow);
            }
            catch
            {
                if (m_volumeHandle != null)
                {
                    m_volumeHandle.Dispose();
                    m_volumeHandle = null;
                }

                throw;
            }

            if (this.FileSystemEntries.Count == 0)
                throw new Exception(Strings.USNHelper.SafeGuardError);
        }
开发者ID:pacificIT,项目名称:Duplicati,代码行数:50,代码来源:USNHelper.cs

示例7: SetFeature

		public bool SetFeature(byte[] data)
		{
			if (!IsConnected && !Connect())
				return false;

			GCHandle handle = GCHandle.Alloc(data, GCHandleType.Pinned);
			int length = data.Length;
			SafeFileHandle safe = new SafeFileHandle(OpenDeviceIO(DeviceInfo.Path, DeviceMode.NonOverlapped, NativeMethods.GENERIC_WRITE), true);
			try
			{
				IntPtr buffer = Marshal.UnsafeAddrOfPinnedArrayElement(data, 0);
				NativeMethods.HidD_SetFeature(safe, buffer, length);
			}
			finally
			{
				handle.Free();
				safe.Dispose();
			}

			return true;
		}
开发者ID:HaKDMoDz,项目名称:GNet,代码行数:21,代码来源:Device.cs

示例8: CreateSharedBackingObjectUsingMemory

        // -----------------------------
        // ---- PAL layer ends here ----
        // -----------------------------

        private static FileStream CreateSharedBackingObjectUsingMemory(
           Interop.Sys.MemoryMappedProtections protections, long capacity)
        {
            // The POSIX shared memory object name must begin with '/'.  After that we just want something short and unique.
            string mapName = "/corefx_map_" + Guid.NewGuid().ToString("N");

            // Determine the flags to use when creating the shared memory object
            Interop.Sys.OpenFlags flags = (protections & Interop.Sys.MemoryMappedProtections.PROT_WRITE) != 0 ?
                Interop.Sys.OpenFlags.O_RDWR :
                Interop.Sys.OpenFlags.O_RDONLY;
            flags |= Interop.Sys.OpenFlags.O_CREAT | Interop.Sys.OpenFlags.O_EXCL; // CreateNew

            // Determine the permissions with which to create the file
            Interop.Sys.Permissions perms = default(Interop.Sys.Permissions);
            if ((protections & Interop.Sys.MemoryMappedProtections.PROT_READ) != 0)
                perms |= Interop.Sys.Permissions.S_IRUSR;
            if ((protections & Interop.Sys.MemoryMappedProtections.PROT_WRITE) != 0)
                perms |= Interop.Sys.Permissions.S_IWUSR;
            if ((protections & Interop.Sys.MemoryMappedProtections.PROT_EXEC) != 0)
                perms |= Interop.Sys.Permissions.S_IXUSR;

            // Create the shared memory object.
            int fd = Interop.Sys.ShmOpen(mapName, flags, (int)perms);
            if (fd < 0)
            {
                Interop.ErrorInfo errorInfo = Interop.Sys.GetLastErrorInfo();
                if (errorInfo.Error == Interop.Error.ENOTSUP)
                {
                    // If ShmOpen is not supported, fall back to file backing object.
                    // Note that the System.Native shim will force this failure on platforms where
                    // the result of native shm_open does not work well with our subsequent call
                    // to mmap.
                    return null;
                }

                throw Interop.GetExceptionForIoErrno(errorInfo);
            }

            SafeFileHandle fileHandle = new SafeFileHandle((IntPtr)fd, ownsHandle: true);
            try
            {
                // Unlink the shared memory object immediatley so that it'll go away once all handles 
                // to it are closed (as with opened then unlinked files, it'll remain usable via
                // the open handles even though it's unlinked and can't be opened anew via its name).
                Interop.CheckIo(Interop.Sys.ShmUnlink(mapName));

                // Give it the right capacity.  We do this directly with ftruncate rather
                // than via FileStream.SetLength after the FileStream is created because, on some systems,
                // lseek fails on shared memory objects, causing the FileStream to think it's unseekable,
                // causing it to preemptively throw from SetLength.
                Interop.CheckIo(Interop.Sys.FTruncate(fd, capacity));

                // Wrap the file descriptor in a stream and return it.
                return new FileStream(fileHandle, TranslateProtectionsToFileAccess(protections));
            }
            catch
            {
                fileHandle.Dispose();
                throw;
            }
        }
开发者ID:nnyamhon,项目名称:corefx,代码行数:65,代码来源:MemoryMappedFile.Unix.cs

示例9: _CloseHandle

 private static void _CloseHandle(SafeFileHandle h)
 {
     try
       {
     if (h != null)
     {
       h.Close();
       h.Dispose();
     }
       }
       catch
       {
     //Eat...
       }
 }
开发者ID:aromis,项目名称:uDrawTablet,代码行数:15,代码来源:PPJoyInterface.cs


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