本文整理汇总了C#中Microsoft.Win32.SafeHandles.SafeFileHandle.DangerousGetHandle方法的典型用法代码示例。如果您正苦于以下问题:C# SafeFileHandle.DangerousGetHandle方法的具体用法?C# SafeFileHandle.DangerousGetHandle怎么用?C# SafeFileHandle.DangerousGetHandle使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类Microsoft.Win32.SafeHandles.SafeFileHandle
的用法示例。
在下文中一共展示了SafeFileHandle.DangerousGetHandle方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: Build_Volume_Mapping
private static readonly int BUF_LEN = 8192 + 8; //8 bytes for the leading USN
#endregion Fields
#region Methods
public static bool Build_Volume_Mapping(SafeFileHandle roothandle, Win32Api.USN_JOURNAL_DATA currentUsnState, Action<Win32Api.UsnEntry> func)
{
Debug.WriteLine("Starting Build_Volume_Mapping");
DateTime startTime = DateTime.Now;
Win32Api.MFT_ENUM_DATA med;
med.StartFileReferenceNumber = 0;
med.LowUsn = 0;
med.HighUsn = currentUsnState.NextUsn;
using(var med_struct = new StructWrapper(med))
using(var rawdata = new Raw_Array_Wrapper(BUF_LEN))
{
uint outBytesReturned = 0;
while(Win32Api.DeviceIoControl(
roothandle.DangerousGetHandle(),
Win32Api.FSCTL_ENUM_USN_DATA,
med_struct.Ptr,
med_struct.Size,
rawdata.Ptr,
rawdata.Size,
out outBytesReturned,
IntPtr.Zero))
{
outBytesReturned = outBytesReturned - sizeof(Int64);
IntPtr pUsnRecord = System.IntPtr.Add(rawdata.Ptr, sizeof(Int64));//need to skip 8 bytes because the first 8 bytes are to a usn number, which isnt in the structure
while(outBytesReturned > 60)
{
var usnEntry = new Win32Api.UsnEntry(pUsnRecord);
pUsnRecord = System.IntPtr.Add(pUsnRecord, (int)usnEntry.RecordLength);
func(usnEntry);
if(usnEntry.RecordLength > outBytesReturned)
outBytesReturned = 0;// prevent overflow
else
outBytesReturned -= usnEntry.RecordLength;
}
Marshal.WriteInt64(med_struct.Ptr, Marshal.ReadInt64(rawdata.Ptr, 0));//read the usn that we skipped and place it into the nextusn
}
var possiblerror = Marshal.GetLastWin32Error();
if(possiblerror < 0)
throw new Win32Exception(possiblerror);
}
Debug.WriteLine("Time took: " + (DateTime.Now - startTime).TotalMilliseconds + "ms");
return true;
}
示例2: Read
public static int Read(SafeFileHandle handle, byte[] buffer, int offset, int count)
{
#if __MonoCS__
int r;
fixed(byte *p = buffer) {
do {
r = (int) Syscall.read (handle.DangerousGetHandle().ToInt32(), p, (ulong) count);
} while (UnixMarshal.ShouldRetrySyscall ((int) r));
if(r == -1) {
int errno = Marshal.GetLastWin32Error();
if (errno == EAGAIN) {
return 0;
}
throw new Win32Exception();
}
return r;
}
#else
return 0;
#endif
}
示例3: ReadConsoleInput
internal static int ReadConsoleInput(SafeFileHandle consoleHandle, ref ConsoleControl.INPUT_RECORD[] buffer)
{
int num = 0;
bool flag = ConsoleControl.NativeMethods.ReadConsoleInput(consoleHandle.DangerousGetHandle(), buffer, buffer.Length, out num);
if (flag)
{
return num;
}
else
{
int lastWin32Error = Marshal.GetLastWin32Error();
HostException hostException = ConsoleControl.CreateHostException(lastWin32Error, "ReadConsoleInput", ErrorCategory.ReadError, ConsoleControlStrings.ReadConsoleInputExceptionTemplate);
throw hostException;
}
}
示例4: GetDiskSize
public static long GetDiskSize(SafeFileHandle Handle)
{
if (Handle.IsInvalid || Handle.IsClosed) throw new Exception("Native.GetDiskSize: Invalid handle specified. It is closed or invalid.");
long size = 0;
uint returnedBytes;
if (DeviceIoControl(Handle.DangerousGetHandle(), (uint)IOCTL_CONTROL_CODE_CONSTANTS.IOCTL_DISK_GET_LENGTH_INFO, IntPtr.Zero, 0, ref size, 8, out returnedBytes, IntPtr.Zero)) return size;
Marshal.ThrowExceptionForHR(Marshal.GetHRForLastWin32Error());
return 0;
}
示例5: SetCompletionPort
private void SetCompletionPort(SafeFileHandle completionPortHandle)
{
int length = Marshal.SizeOf(typeof(NativeMethods.JobObjectAssociateCompletionPort));
IntPtr completionPortPtr = IntPtr.Zero;
try
{
var completionPort = new NativeMethods.JobObjectAssociateCompletionPort
{
CompletionKey = IntPtr.Zero,
CompletionPortHandle = completionPortHandle.DangerousGetHandle(),
};
completionPortPtr = Marshal.AllocHGlobal(length);
Marshal.StructureToPtr(completionPort, completionPortPtr, false);
if (!NativeMethods.SetInformationJobObject(handle, NativeMethods.JobObjectInfoClass.AssociateCompletionPortInformation, completionPortPtr, length))
{
throw new Win32Exception(Marshal.GetLastWin32Error());
}
}
finally
{
if (completionPortPtr != IntPtr.Zero)
Marshal.FreeHGlobal(completionPortPtr);
}
}
示例6: GetConsoleScreenBufferInfo
/// <summary>
/// Wraps Win32 GetConsoleScreenBufferInfo
/// Returns Console Screen Buffer Info
/// </summary>
/// <param name="consoleHandle">
///
/// Handle for the console where the screen buffer info is obtained
///
/// </param>
/// <returns>
///
/// info about the screen buffer. See the definition of CONSOLE_SCREEN_BUFFER_INFO
///
/// </returns>
/// <exception cref="HostException">
/// If Win32's GetConsoleScreenBufferInfo fails
/// </exception>
internal static CONSOLE_SCREEN_BUFFER_INFO GetConsoleScreenBufferInfo(ConsoleHandle consoleHandle)
{
Dbg.Assert(!consoleHandle.IsInvalid, "ConsoleHandle is not valid");
Dbg.Assert(!consoleHandle.IsClosed, "ConsoleHandle is closed");
CONSOLE_SCREEN_BUFFER_INFO bufferInfo;
bool result = NativeMethods.GetConsoleScreenBufferInfo(consoleHandle.DangerousGetHandle(), out bufferInfo);
if (result == false)
{
int err = Marshal.GetLastWin32Error();
HostException e = CreateHostException(err, "GetConsoleScreenBufferInfo",
ErrorCategory.ResourceUnavailable, ConsoleControlStrings.GetConsoleScreenBufferInfoExceptionTemplate);
throw e;
}
return bufferInfo;
}
示例7: GetNumberOfConsoleInputEvents
/// <summary>
/// Wraps Win32 GetNumberOfConsoleInputEvents
/// </summary>
/// <param name="consoleHandle">
///
/// handle for the console where the number of console input events is obtained
///
/// </param>
/// <returns>
///
/// number of console input events
///
/// </returns>
/// <exception cref="HostException">
/// If Win32's GetNumberOfConsoleInputEvents fails
/// </exception>
internal static int GetNumberOfConsoleInputEvents(ConsoleHandle consoleHandle)
{
Dbg.Assert(!consoleHandle.IsInvalid, "ConsoleHandle is not valid");
Dbg.Assert(!consoleHandle.IsClosed, "ConsoleHandle is closed");
DWORD numEvents;
bool result = NativeMethods.GetNumberOfConsoleInputEvents(consoleHandle.DangerousGetHandle(), out numEvents);
if (result == false)
{
int err = Marshal.GetLastWin32Error();
HostException e = CreateHostException(err, "GetNumberOfConsoleInputEvents",
ErrorCategory.ReadError, ConsoleControlStrings.GetNumberOfConsoleInputEventsExceptionTemplate);
throw e;
}
return (int)numEvents;
}
示例8: ReadConsole
/// <summary>
///
/// Reads input from the console device according to the mode in effect (see GetMode, SetMode)
///
/// </summary>
/// <param name="consoleHandle"></param>
///
/// Handle to the console device returned by GetInputHandle
///
/// <param name="initialContent">
///
/// Initial contents of the edit buffer, if any. charactersToRead should be at least as large as the length of this string.
///
/// </param>
/// <param name="charactersToRead">
///
/// Number of characters to read from the device.
///
/// </param>
/// <param name="endOnTab">
///
/// true to allow the user to terminate input by hitting the tab or shift-tab key, in addition to the enter key
///
/// </param>
/// <param name="keyState">
///
/// bit mask indicating the state of the control/shift keys at the point input was terminated.
///
/// </param>
/// <returns></returns>
/// <exception cref="HostException">
///
/// If Win32's ReadConsole fails
///
/// </exception>
internal static string ReadConsole(ConsoleHandle consoleHandle, string initialContent,
int charactersToRead, bool endOnTab, out uint keyState)
{
Dbg.Assert(!consoleHandle.IsInvalid, "ConsoleHandle is not valid");
Dbg.Assert(!consoleHandle.IsClosed, "ConsoleHandle is closed");
Dbg.Assert(initialContent != null, "if no initial content is desired, pass String.Empty");
keyState = 0;
CONSOLE_READCONSOLE_CONTROL control = new CONSOLE_READCONSOLE_CONTROL();
control.nLength = (ULONG)Marshal.SizeOf(control);
control.nInitialChars = (ULONG)initialContent.Length;
control.dwControlKeyState = 0;
if (endOnTab)
{
const int TAB = 0x9;
control.dwCtrlWakeupMask = (1 << TAB);
}
DWORD charsReadUnused = 0;
StringBuilder buffer = new StringBuilder(initialContent, charactersToRead);
bool result =
NativeMethods.ReadConsole(
consoleHandle.DangerousGetHandle(),
buffer,
(DWORD)charactersToRead,
out charsReadUnused,
ref control);
keyState = control.dwControlKeyState;
if (result == false)
{
int err = Marshal.GetLastWin32Error();
HostException e = CreateHostException(err, "ReadConsole",
ErrorCategory.ReadError, ConsoleControlStrings.ReadConsoleExceptionTemplate);
throw e;
}
if (charsReadUnused > (uint)buffer.Length)
charsReadUnused = (uint)buffer.Length;
return buffer.ToString(0, (int)charsReadUnused);
}
示例9: SetConsoleCursorInfo
/// <summary>
/// Wraps Win32 SetConsoleCursorInfo
/// </summary>
/// <param name="consoleHandle">
///
/// handle for the console where cursor info is set
///
/// </param>
/// <param name="cursorInfo">
///
/// cursor info to set the cursor
///
/// </param>
/// <exception cref="HostException">
/// If Win32's SetConsoleCursorInfo fails
/// </exception>
internal static void SetConsoleCursorInfo(ConsoleHandle consoleHandle, CONSOLE_CURSOR_INFO cursorInfo)
{
Dbg.Assert(!consoleHandle.IsInvalid, "ConsoleHandle is not valid");
Dbg.Assert(!consoleHandle.IsClosed, "ConsoleHandle is closed");
bool result = NativeMethods.SetConsoleCursorInfo(consoleHandle.DangerousGetHandle(), ref cursorInfo);
if (result == false)
{
int err = Marshal.GetLastWin32Error();
HostException e = CreateHostException(err, "SetConsoleCursorInfo",
ErrorCategory.ResourceUnavailable, ConsoleControlStrings.SetConsoleCursorInfoExceptionTemplate);
throw e;
}
}
示例10: WriteConsoleOutputPlain
private static void WriteConsoleOutputPlain(ConsoleHandle consoleHandle, Coordinates origin, BufferCell[,] contents)
{
int rows = contents.GetLength(0);
int cols = contents.GetLength(1);
if ((rows <= 0) || cols <= 0)
{
tracer.WriteLine("contents passed in has 0 rows and columns");
return;
}
int bufferLimit = 2 * 1024; // Limit is 8K bytes as each CHAR_INFO takes 4 bytes
COORD bufferCoord;
bufferCoord.X = 0;
bufferCoord.Y = 0;
// keeps track of which screen area write
SMALL_RECT writeRegion;
writeRegion.Top = (short)origin.Y;
int rowsRemaining = rows;
while (rowsRemaining > 0)
{
// Iteration of columns is nested inside iteration of rows.
// If the size of contents exceeds the buffer limit, writing is
// done in blocks of size equal to the bufferlimit from left to right
// then top to bottom.
// For each iteration of rows,
// - writeRegion.Left and bufferSize.X are reset
// - rowsRemaining, writeRegion.Top, writeRegion.Bottom, and bufferSize.Y
// are updated
// For each iteration of columns,
// - writeRegion.Left, writeRegion.Right and bufferSize.X are updated
writeRegion.Left = (short)origin.X;
COORD bufferSize;
bufferSize.X = (short)Math.Min(cols, bufferLimit);
bufferSize.Y = (short)Math.Min
(
rowsRemaining,
bufferLimit / bufferSize.X
);
writeRegion.Bottom = (short)(writeRegion.Top + bufferSize.Y - 1);
// atRow is at which row of contents a particular iteration is operating
int atRow = rows - rowsRemaining + contents.GetLowerBound(0);
// number of columns yet to be written
int colsRemaining = cols;
while (colsRemaining > 0)
{
writeRegion.Right = (short)(writeRegion.Left + bufferSize.X - 1);
// atCol is at which column of contents a particular iteration is operating
int atCol = cols - colsRemaining + contents.GetLowerBound(1);
CHAR_INFO[] characterBuffer = new CHAR_INFO[bufferSize.Y * bufferSize.X];
// copy characterBuffer to contents;
for (int r = atRow, characterBufferIndex = 0;
r < bufferSize.Y + atRow; r++)
{
for (int c = atCol; c < bufferSize.X + atCol; c++, characterBufferIndex++)
{
characterBuffer[characterBufferIndex].UnicodeChar =
(ushort)contents[r, c].Character;
characterBuffer[characterBufferIndex].Attributes =
ColorToWORD(contents[r, c].ForegroundColor, contents[r, c].BackgroundColor);
}
}
// Now writeRegion, bufferSize and characterBuffer are updated.
// Call NativeMethods.WriteConsoleOutput
bool result =
NativeMethods.WriteConsoleOutput(
consoleHandle.DangerousGetHandle(),
characterBuffer,
bufferSize,
bufferCoord,
ref writeRegion);
if (result == false)
{
// When WriteConsoleOutput fails, half bufferLimit
if (bufferLimit < 2)
{
int err = Marshal.GetLastWin32Error();
HostException e = CreateHostException(err, "WriteConsoleOutput",
ErrorCategory.WriteError, ConsoleControlStrings.WriteConsoleOutputExceptionTemplate);
throw e;
}
bufferLimit /= 2;
if (cols == colsRemaining)
{
// if cols == colsRemaining, nothing is guaranteed written in this pass and
//.........这里部分代码省略.........
示例11: WriteConsoleOutputCJK
//.........这里部分代码省略.........
// if bit 1 is 1 and bit 2 is 0, the font is a vector font; if bit 1 is 0 and bit 2 is set, or if both
// bits are 1, the font is true type. Bit 3 is 1 if the font is a device font; otherwise, it is 0.
// We only care about the bit 1 and 2, which indicate the font type.
// There are only two font type defined for the Console, at
// HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Console\.
// Console\Nls --- national language supports
// Console\RasterFonts --- raster type font
// Console\TrueTypeFont --- true type font
// For CJK characters, if it's TrueType, we need to output the trailing character marked with "Trailing_byte"
// attribute. But if it's RasterFont, we ignore the trailing character, and the "Leading_byte"/"Trailing_byte"
// attributes are not effective at all when reading the character from the console buffer.
if (lastCharIsLeading && trueTypeInUse)
{
// For TrueType Font, we output the trailing byte with "Trailing_byte" attribute
characterBuffer[characterBufferIndex].UnicodeChar = lastLeadingCell.Character;
characterBuffer[characterBufferIndex].Attributes =
(ushort)(ColorToWORD(contents[r, c].ForegroundColor, contents[r, c].BackgroundColor)
| (ushort)NativeMethods.CHAR_INFO_Attributes.COMMON_LVB_TRAILING_BYTE);
}
else
{
// We don't output anything for this cell if Raster font is in use, or if the last cell is not a leading byte
characterBufferIndex--;
}
lastCharIsLeading = false;
}
}
}
// Now writeRegion, bufferSize and characterBuffer are updated.
// Call NativeMethods.WriteConsoleOutput
bool result;
if ((rowType & BufferCellArrayRowType.RightLeading) != 0 &&
colsRemaining == bufferSize.X)
{
COORD bSize = bufferSize;
bSize.X++;
SMALL_RECT wRegion = writeRegion;
wRegion.Right++;
// Suppress the PreFAST warning about not using Marshal.GetLastWin32Error() to
// get the error code.
#pragma warning disable 56523
result = NativeMethods.WriteConsoleOutput(
consoleHandle.DangerousGetHandle(),
characterBuffer,
bSize,
bufferCoord,
ref wRegion);
}
else
{
// Suppress the PreFAST warning about not using Marshal.GetLastWin32Error() to
// get the error code.
#pragma warning disable 56523
result = NativeMethods.WriteConsoleOutput(
consoleHandle.DangerousGetHandle(),
characterBuffer,
bufferSize,
bufferCoord,
ref writeRegion);
}
if (result == false)
{
// When WriteConsoleOutput fails, half bufferLimit
if (bufferLimit < 2)
{
int err = Marshal.GetLastWin32Error();
HostException e = CreateHostException(err, "WriteConsoleOutput",
ErrorCategory.WriteError, ConsoleControlStrings.WriteConsoleOutputExceptionTemplate);
throw e;
}
bufferLimit /= 2;
if (cols == colsRemaining)
{
// if cols == colsRemaining, nothing is guaranteed written in this pass and
// the unwritten area is still rectangular
bufferSize.Y = 0;
break;
}
else
{
// some areas have been written. This could only happen when the number of columns
// to write is larger than bufferLimit. In that case, the algorithm writes one row
// at a time => bufferSize.Y == 1. Then, we can safely leave bufferSize.Y unchanged
// to retry with a smaller bufferSize.X.
Dbg.Assert(bufferSize.Y == 1, string.Format(CultureInfo.InvariantCulture, "bufferSize.Y should be 1, but is {0}", bufferSize.Y));
bufferSize.X = (short)Math.Min(colsRemaining, bufferLimit);
continue;
}
}
colsRemaining -= bufferSize.X;
writeRegion.Left += bufferSize.X;
bufferSize.X = (short)Math.Min(colsRemaining, bufferLimit);
} // column iteration
rowsRemaining -= bufferSize.Y;
writeRegion.Top += bufferSize.Y;
} // row iteration
}
示例12: SetConsoleScreenBufferSize
/// <summary>
/// set the output buffer's size
/// </summary>
/// <param name="consoleHandle"></param>
/// <param name="newSize"></param>
/// <exception cref="HostException">
/// If Win32's SetConsoleScreenBufferSize fails
/// </exception>
internal static void SetConsoleScreenBufferSize(ConsoleHandle consoleHandle, Size newSize)
{
Dbg.Assert(!consoleHandle.IsInvalid, "ConsoleHandle is not valid");
Dbg.Assert(!consoleHandle.IsClosed, "ConsoleHandle is closed");
COORD s;
s.X = (short)newSize.Width;
s.Y = (short)newSize.Height;
bool result = NativeMethods.SetConsoleScreenBufferSize(consoleHandle.DangerousGetHandle(), s);
if (result == false)
{
int err = Marshal.GetLastWin32Error();
HostException e = CreateHostException(err, "SetConsoleScreenBufferSize",
ErrorCategory.ResourceUnavailable, ConsoleControlStrings.SetConsoleScreenBufferSizeExceptionTemplate);
throw e;
}
}
示例13: GetUsnJournalEntries
public static void GetUsnJournalEntries(SafeFileHandle roothandle, Win32Api.USN_JOURNAL_DATA previousUsnState,
UInt32 reasonMask,
out List<Win32Api.UsnEntry> usnEntries,
out Win32Api.USN_JOURNAL_DATA newUsnState)
{
usnEntries = new List<Win32Api.UsnEntry>();
newUsnState = new Win32Api.USN_JOURNAL_DATA();
QueryUsnJournal(roothandle, ref newUsnState);
Win32Api.READ_USN_JOURNAL_DATA rujd = new Win32Api.READ_USN_JOURNAL_DATA();
rujd.StartUsn = previousUsnState.NextUsn;
rujd.ReasonMask = reasonMask;
rujd.ReturnOnlyOnClose = 0;
rujd.Timeout = 0;
rujd.bytesToWaitFor = 0;
rujd.UsnJournalId = previousUsnState.UsnJournalID;
using(var med_struct = new StructWrapper(rujd))
using(var rawdata = new Raw_Array_Wrapper(BUF_LEN))
{
uint outBytesReturned = 0;
var nextusn = previousUsnState.NextUsn;
while(nextusn < newUsnState.NextUsn && Win32Api.DeviceIoControl(
roothandle.DangerousGetHandle(),
Win32Api.FSCTL_READ_USN_JOURNAL,
med_struct.Ptr,
med_struct.Size,
rawdata.Ptr,
rawdata.Size,
out outBytesReturned,
IntPtr.Zero))
{
outBytesReturned = outBytesReturned - sizeof(Int64);
IntPtr pUsnRecord = System.IntPtr.Add(rawdata.Ptr, sizeof(Int64));//point safe arithmetic!~!!
while(outBytesReturned > 60) // while there are at least one entry in the usn journal
{
var usnEntry = new Win32Api.UsnEntry(pUsnRecord);
if(usnEntry.USN > newUsnState.NextUsn)
break;
usnEntries.Add(usnEntry);
pUsnRecord = System.IntPtr.Add(pUsnRecord, (int)usnEntry.RecordLength);//point safe arithmetic!~!!
outBytesReturned -= usnEntry.RecordLength;
}
nextusn = Marshal.ReadInt64(rawdata.Ptr, 0);
Marshal.WriteInt64(med_struct.Ptr, nextusn);//read the usn that we skipped and place it into the nextusn
}
}
}
示例14: QueryUsnJournal
public static void QueryUsnJournal(SafeFileHandle roothandle, ref Win32Api.USN_JOURNAL_DATA usnJournalState)
{
int sizeUsnJournalState = Marshal.SizeOf(usnJournalState);
UInt32 cb;
if(!Win32Api.DeviceIoControl(
roothandle.DangerousGetHandle(),
Win32Api.FSCTL_QUERY_USN_JOURNAL,
IntPtr.Zero,
0,
out usnJournalState,
sizeUsnJournalState,
out cb,
IntPtr.Zero))
{
throw new Win32Exception(Marshal.GetLastWin32Error());
}
}
示例15: SetConsoleCursorPosition
/// <summary>
/// Wraps Win32 SetConsoleCursorPosition
/// </summary>
/// <param name="consoleHandle">
///
/// handle for the console where cursor position is set
///
/// </param>
/// <param name="cursorPosition">
///
/// location to which the cursor will be set
///
/// </param>
/// <exception cref="HostException">
/// If Win32's SetConsoleCursorPosition fails
/// </exception>
internal static void SetConsoleCursorPosition(ConsoleHandle consoleHandle, Coordinates cursorPosition)
{
Dbg.Assert(!consoleHandle.IsInvalid, "ConsoleHandle is not valid");
Dbg.Assert(!consoleHandle.IsClosed, "ConsoleHandle is closed");
ConsoleControl.COORD c;
c.X = (short)cursorPosition.X;
c.Y = (short)cursorPosition.Y;
bool result = NativeMethods.SetConsoleCursorPosition(consoleHandle.DangerousGetHandle(), c);
if (result == false)
{
int err = Marshal.GetLastWin32Error();
HostException e = CreateHostException(err, "SetConsoleCursorPosition",
ErrorCategory.ResourceUnavailable, ConsoleControlStrings.SetConsoleCursorPositionExceptionTemplate);
throw e;
}
}