本文整理汇总了C#中SafeFileHandle类的典型用法代码示例。如果您正苦于以下问题:C# SafeFileHandle类的具体用法?C# SafeFileHandle怎么用?C# SafeFileHandle使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
SafeFileHandle类属于命名空间,在下文中一共展示了SafeFileHandle类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的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;
}
示例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;
}
示例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();
}
}
}
示例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;
}
示例5: CreateFileMapping
internal static extern SafeMemoryMappedFileHandle CreateFileMapping(
SafeFileHandle hFile,
ref SECURITY_ATTRIBUTES lpFileMappingAttributes,
int flProtect,
int dwMaximumSizeHigh,
int dwMaximumSizeLow,
string lpName);
示例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;
}
示例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;
}
}
示例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;
}
}
示例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
示例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;
}
示例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;
}
}
示例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;
}
示例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);
}
示例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;
}
示例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);
}