Here are the examples of the csharp api System.Runtime.InteropServices.Marshal.GetLastWin32Error() taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
1363 Examples
19
Source : TCPUDPServer.cs
with MIT License
from 0x0ade
with MIT License
from 0x0ade
public void Start() {
Logger.Log(LogLevel.CRI, "tcpudp", $"Startup on port {Server.Settings.MainPort}");
TCPListener = new(IPAddress.IPv6Any, Server.Settings.MainPort);
TCPListener.Server.SetSocketOption(SocketOptionLevel.IPv6, SocketOptionName.IPv6Only, false);
TCPListener.Start();
TCPListenerThread = new(TCPListenerLoop) {
Name = $"TCPUDPServer TCPListener ({GetHashCode()})",
IsBackground = true
};
TCPListenerThread.Start();
int numUdpThreads = Server.Settings.NumUDPThreads;
bool udpSend = Server.Settings.UDPSend;
if (numUdpThreads <= 0) {
// Determine suitable number of UDP threads
// On Windows, having multiple threads isn't an advantage at all, so start only one
// On Linux/MacOS, spawn one thread for each logical core
if (Environment.OSVersion.Platform != PlatformID.Unix && Environment.OSVersion.Platform != PlatformID.MacOSX)
numUdpThreads = 1;
else
numUdpThreads = Environment.ProcessorCount;
}
Logger.Log(LogLevel.CRI, "tcpudp", $"Starting {numUdpThreads} UDP threads");
UDPs = new UdpClient[numUdpThreads];
UDPReadThreads = new Thread[numUdpThreads];
for (int i = 0; i < numUdpThreads; i++) {
Socket udpSocket = new(AddressFamily.InterNetworkV6, SocketType.Dgram, ProtocolType.Udp);
udpSocket.SetSocketOption(SocketOptionLevel.IPv6, SocketOptionName.IPv6Only, false);
if (numUdpThreads > 1) {
udpSocket.SetSocketOption(SocketOptionLevel.IPv6, SocketOptionName.ReuseAddress, true);
// Some Linux/MacOS runtimes don't automatically set SO_REUSEPORT (the option we care about), so set it directly, just in case
if (Environment.OSVersion.Platform == PlatformID.Unix || Environment.OSVersion.Platform == PlatformID.MacOSX) {
if (setsockopt(udpSocket.Handle, SOL_SOCKET, SO_REUSEPORT, new[] { 1 }, sizeof(int)) < 0) {
// Even though the method is named GetLastWin32Error, it still works on other platforms
// NET 6.0 added the better named method GetLastPInvokeError, which does the same thing
// However, still use GetLastWin32Error to remain compatible with the net452 build target
Logger.Log(LogLevel.WRN, "tcpudp", $"Failed enabling UDP socket option SO_REUSEPORT for socket {i}: {Marshal.GetLastWin32Error()}");
}
} else if (i == 0) {
// We only have an advantage with multiple threads when SO_REUSEPORT is supported
// It tells the Linux kernel to distribute incoming packets evenly among all sockets bound to that port
// However, Windows doesn't support it, and it's SO_REUSEADDR behaviour is that only one socket will receive everything
// As such only one thread will handle all messages and actually do any work
// TODO BSD/MacOS also supports SO_REUSEPORT, but I couldn't find any explicit mention of the load-balancing behaviour we're looking for
// So it might be better to also warn on BSD/MacOS, or make this feature Linux exclusive
Logger.Log(LogLevel.WRN, "tcpudp", "Starting more than one UDP thread on a platform without SO_REUSEPORT!");
}
}
udpSocket.Bind(new IPEndPoint(IPAddress.IPv6Any, Server.Settings.MainPort));
UDPs[i] = new(AddressFamily.InterNetworkV6);
UDPs[i].Client.Dispose();
UDPs[i].Client = udpSocket;
// This is neccessary, as otherwise i could increment before the thread function is called
int idx = i;
UDPReadThreads[i] = new(() => UDPReadLoop(idx, udpSend)) {
Name = $"TCPUDPServer UDPRead {i} ({GetHashCode()})",
IsBackground = true
};
UDPReadThreads[i].Start();
}
19
Source : ProxySetting.cs
with GNU General Public License v3.0
from 2dust
with GNU General Public License v3.0
from 2dust
public static bool SetProxy(string strProxy, string exceptions, int type)
{
InternetPerConnOptionList list = new InternetPerConnOptionList();
int optionCount = 1;
if (type == 1)
{
optionCount = 1;
}
else if (type == 2 || type == 4)
{
optionCount = Utils.IsNullOrEmpty(exceptions) ? 2 : 3;
}
int m_Int = (int)PerConnFlags.PROXY_TYPE_DIRECT;
PerConnOption m_Option = PerConnOption.INTERNET_PER_CONN_FLAGS;
if (type == 2)
{
m_Int = (int)(PerConnFlags.PROXY_TYPE_DIRECT | PerConnFlags.PROXY_TYPE_PROXY);
m_Option = PerConnOption.INTERNET_PER_CONN_PROXY_SERVER;
}
else if (type == 4)
{
m_Int = (int)(PerConnFlags.PROXY_TYPE_DIRECT | PerConnFlags.PROXY_TYPE_AUTO_PROXY_URL);
m_Option = PerConnOption.INTERNET_PER_CONN_AUTOCONFIG_URL;
}
//int optionCount = Utils.IsNullOrEmpty(strProxy) ? 1 : (Utils.IsNullOrEmpty(exceptions) ? 2 : 3);
InternetConnectionOption[] options = new InternetConnectionOption[optionCount];
// USE a proxy server ...
options[0].m_Option = PerConnOption.INTERNET_PER_CONN_FLAGS;
//options[0].m_Value.m_Int = (int)((optionCount < 2) ? PerConnFlags.PROXY_TYPE_DIRECT : (PerConnFlags.PROXY_TYPE_DIRECT | PerConnFlags.PROXY_TYPE_PROXY));
options[0].m_Value.m_Int = m_Int;
// use THIS proxy server
if (optionCount > 1)
{
options[1].m_Option = m_Option;
options[1].m_Value.m_StringPtr = Marshal.StringToHGlobalAuto(strProxy);
// except for these addresses ...
if (optionCount > 2)
{
options[2].m_Option = PerConnOption.INTERNET_PER_CONN_PROXY_BYPreplaced;
options[2].m_Value.m_StringPtr = Marshal.StringToHGlobalAuto(exceptions);
}
}
// default stuff
list.dwSize = Marshal.SizeOf(list);
list.szConnection = IntPtr.Zero;
list.dwOptionCount = options.Length;
list.dwOptionError = 0;
int optSize = Marshal.SizeOf(typeof(InternetConnectionOption));
// make a pointer out of all that ...
IntPtr optionsPtr = Marshal.AllocCoTaskMem(optSize * options.Length);
// copy the array over into that spot in memory ...
for (int i = 0; i < options.Length; ++i)
{
if (Environment.Is64BitOperatingSystem)
{
IntPtr opt = new IntPtr(optionsPtr.ToInt64() + (i * optSize));
Marshal.StructureToPtr(options[i], opt, false);
}
else
{
IntPtr opt = new IntPtr(optionsPtr.ToInt32() + (i * optSize));
Marshal.StructureToPtr(options[i], opt, false);
}
}
list.options = optionsPtr;
// and then make a pointer out of the whole list
IntPtr ipcoListPtr = Marshal.AllocCoTaskMem((int)list.dwSize);
Marshal.StructureToPtr(list, ipcoListPtr, false);
// and finally, call the API method!
int returnvalue = NativeMethods.InternetSetOption(IntPtr.Zero,
InternetOption.INTERNET_OPTION_PER_CONNECTION_OPTION,
ipcoListPtr, list.dwSize) ? -1 : 0;
if (returnvalue == 0)
{ // get the error codes, they might be helpful
returnvalue = Marshal.GetLastWin32Error();
}
// FREE the data ASAP
Marshal.FreeCoTaskMem(optionsPtr);
Marshal.FreeCoTaskMem(ipcoListPtr);
if (returnvalue > 0)
{ // throw the error codes, they might be helpful
//throw new Win32Exception(Marshal.GetLastWin32Error());
}
return (returnvalue < 0);
}
19
Source : Job.cs
with GNU General Public License v3.0
from 2dust
with GNU General Public License v3.0
from 2dust
public bool AddProcess(IntPtr processHandle)
{
bool succ = replacedignProcessToJobObject(handle, processHandle);
if (!succ)
{
Utils.SaveLog("Failed to call replacedignProcessToJobObject! GetLastError=" + Marshal.GetLastWin32Error());
}
return succ;
}
19
Source : Helpers.cs
with MIT License
from 71
with MIT License
from 71
internal static void AllowRW(IntPtr address)
{
if (IsARM)
return;
if (IsWindows)
{
if (VirtualProtect(address, new UIntPtr(1), 0x40 /* PAGE_EXECUTE_READWRITE */, out var _))
return;
goto Error;
}
long pagesize = IsLinux ? LinuxGetPageSize() : OsxGetPageSize();
long start = address.ToInt64();
long pagestart = start & -pagesize;
int buffsize = IntPtr.Size == sizeof(int) ? 6 : 12;
if (IsLinux && LinuxProtect(new IntPtr(pagestart), (ulong) (start + buffsize - pagestart), 0x7 /* PROT_READ_WRITE_EXEC */) == 0)
return;
if (!IsLinux && OsxProtect(new IntPtr(pagestart), (ulong) (start + buffsize - pagestart), 0x7 /* PROT_READ_WRITE_EXEC */) == 0)
return;
Error:
throw new Exception($"Unable to make method memory readable and writable. Error code: {Marshal.GetLastWin32Error()}");
}
19
Source : Ryder.Lightweight.cs
with MIT License
from 71
with MIT License
from 71
internal static void AllowRW(IntPtr address)
{
if (IsARM)
return;
if (IsWindows)
{
if (VirtualProtect(address, new UIntPtr(1), 0x40 /* PAGE_EXECUTE_READWRITE */, out var _))
return;
goto Error;
}
long pagesize = IsLinux ? LinuxGetPageSize() : OsxGetPageSize();
long start = address.ToInt64();
long pagestart = start & -pagesize;
int buffsize = IntPtr.Size == sizeof(int) ? 6 : 12;
if (IsLinux && LinuxProtect(new IntPtr(pagestart), (ulong)(start + buffsize - pagestart), 0x7 /* PROT_READ_WRITE_EXEC */) == 0)
return;
if (!IsLinux && OsxProtect(new IntPtr(pagestart), (ulong)(start + buffsize - pagestart), 0x7 /* PROT_READ_WRITE_EXEC */) == 0)
return;
Error:
throw new Exception($"Unable to make method memory readable and writable. Error code: {Marshal.GetLastWin32Error()}");
}
19
Source : Native.cs
with MIT License
from 944095635
with MIT License
from 944095635
public static IntPtr SetWindowLong(IntPtr hWnd, int nIndex, IntPtr dwNewLong)
{
int error = 0;
IntPtr result = IntPtr.Zero;
// Win32 SetWindowLong doesn't clear error on success
SetLastError(0);
if (IntPtr.Size == 4)
{
// use SetWindowLong
Int32 tempResult = IntSetWindowLong(hWnd, nIndex, IntPtrToInt32(dwNewLong));
error = Marshal.GetLastWin32Error();
result = new IntPtr(tempResult);
}
else
{
// use SetWindowLongPtr
result = SetWindowLongPtr(hWnd, nIndex, dwNewLong);
error = Marshal.GetLastWin32Error();
}
if ((result == IntPtr.Zero) && (error != 0))
{
throw new System.ComponentModel.Win32Exception(error);
}
return result;
}
19
Source : UacHelper.cs
with GNU General Public License v3.0
from AaronKelley
with GNU General Public License v3.0
from AaronKelley
public static bool IsProcessElevated()
{
if (IsUacEnabled())
{
if (!OpenProcessToken(Process.GetCurrentProcess().Handle, TOKEN_READ, out IntPtr tokenHandle))
{
throw new ApplicationException("Could not get process token. Win32 Error Code: " + Marshal.GetLastWin32Error());
}
try
{
TokenElevationType elevationResult = TokenElevationType.TokenElevationTypeDefault;
int elevationResultSize = Marshal.SizeOf(Enum.GetUnderlyingType(elevationResult.GetType()));
uint returnedSize = 0;
IntPtr elevationTypePtr = Marshal.AllocHGlobal(elevationResultSize);
try
{
bool success = GetTokenInformation(tokenHandle, TokenInformationClreplaced.TokenElevationType, elevationTypePtr, (uint)elevationResultSize, out returnedSize);
if (success)
{
elevationResult = (TokenElevationType)Marshal.ReadInt32(elevationTypePtr);
bool isProcessAdmin = elevationResult == TokenElevationType.TokenElevationTypeFull;
return isProcessAdmin;
}
else
{
throw new ApplicationException("Unable to determine the current elevation.");
}
}
finally
{
if (elevationTypePtr != IntPtr.Zero)
{
Marshal.FreeHGlobal(elevationTypePtr);
}
}
}
finally
{
if (tokenHandle != IntPtr.Zero)
{
CloseHandle(tokenHandle);
}
}
}
else
{
WindowsIdenreplacedy idenreplacedy = WindowsIdenreplacedy.GetCurrent();
WindowsPrincipal principal = new(idenreplacedy);
bool result = principal.IsInRole(WindowsBuiltInRole.Administrator) || principal.IsInRole(0x200); // 0x200 = Domain Administrator
return result;
}
}
19
Source : DellSmbiosBzh.cs
with GNU General Public License v3.0
from AaronKelley
with GNU General Public License v3.0
from AaronKelley
private static bool RemoveDriver()
{
IntPtr serviceManagerHandle;
IntPtr serviceHandle;
bool result;
StopDriver();
serviceManagerHandle = ServiceMethods.OpenSCManager(null, null, ServiceAccess.ServiceManagerAllAccess);
if (serviceManagerHandle == IntPtr.Zero)
{
return false;
}
serviceHandle = ServiceMethods.OpenService(serviceManagerHandle, DriverName, ServiceAccess.AllAccess);
ServiceMethods.CloseServiceHandle(serviceManagerHandle);
if (serviceManagerHandle == IntPtr.Zero)
{
return false;
}
result = ServiceMethods.QueryServiceConfig(serviceHandle, IntPtr.Zero, 0, out int bytesNeeded);
if ((ErrorCode)Marshal.GetLastWin32Error() == ErrorCode.InsufficientBuffer)
{
IntPtr serviceConfigurationPtr = Marshal.AllocHGlobal(bytesNeeded);
result = ServiceMethods.QueryServiceConfig(serviceHandle, serviceConfigurationPtr, bytesNeeded, out _);
QueryServiceConfig serviceConfiguration = (QueryServiceConfig) Marshal.PtrToStructure(serviceConfigurationPtr, typeof(QueryServiceConfig));
if (!result)
{
Marshal.FreeHGlobal(serviceConfigurationPtr);
ServiceMethods.CloseServiceHandle(serviceHandle);
return result;
}
// If service is set to load automatically, don't delete it!
if (serviceConfigurationPtr != IntPtr.Zero && serviceConfiguration.startType == ServiceStartType.DemandStart)
{
result = ServiceMethods.DeleteService(serviceHandle);
}
Marshal.FreeHGlobal(serviceConfigurationPtr);
}
ServiceMethods.CloseServiceHandle(serviceHandle);
return result;
}
19
Source : DellSmbiosBzh.cs
with GNU General Public License v3.0
from AaronKelley
with GNU General Public License v3.0
from AaronKelley
private static bool StartDriver()
{
IntPtr serviceManagerHandle;
IntPtr serviceHandle;
bool result;
serviceManagerHandle = ServiceMethods.OpenSCManager(null, null, ServiceAccess.ServiceManagerAllAccess);
if (serviceManagerHandle != IntPtr.Zero)
{
serviceHandle = ServiceMethods.OpenService(serviceManagerHandle, DriverName, ServiceAccess.AllAccess);
ServiceMethods.CloseServiceHandle(serviceManagerHandle);
if (serviceHandle != IntPtr.Zero)
{
result = ServiceMethods.StartService(serviceHandle, 0, null) || (ErrorCode)Marshal.GetLastWin32Error() == ErrorCode.ServiceAlreadyRunning;
ServiceMethods.CloseServiceHandle(serviceHandle);
}
else
{
return false;
}
}
else
{
return false;
}
return result;
}
19
Source : WindowHooks.cs
with GNU General Public License v3.0
from Adam-Wilkinson
with GNU General Public License v3.0
from Adam-Wilkinson
public static Rectangle CurrentMonitorSize()
{
NativeMethods.GetCursorPos(out POINT lpPoint);
IntPtr lPrimaryScreen = NativeMethods.MonitorFromPoint(lpPoint, NativeMethods.MonitorOptions.MONITOR_DEFAULTTOPRIMARY);
MONITORINFO lPrimaryScreenInfo = new();
lPrimaryScreenInfo.cbSize = (uint)Marshal.SizeOf(lPrimaryScreenInfo);
if (NativeMethods.GetMonitorInfo(lPrimaryScreen, lPrimaryScreenInfo) == false)
{
Debug.WriteLine(Marshal.GetLastWin32Error());
return new Rectangle();
}
return new Rectangle { Rect = lPrimaryScreenInfo.rcWork };
}
19
Source : WindowHooks.cs
with GNU General Public License v3.0
from Adam-Wilkinson
with GNU General Public License v3.0
from Adam-Wilkinson
private static bool MonitorEnumCallBack(IntPtr hMonitor, IntPtr hdcMonitor, ref RECT lprcMonitor, IntPtr dwData)
{
Debug.WriteLine(hMonitor);
MONITORINFO mon_info = new();
mon_info.cbSize = (uint)Marshal.SizeOf(mon_info);
NativeMethods.GetMonitorInfo(hMonitor, mon_info);
Debug.WriteLine(Marshal.GetLastWin32Error());
AllMonitorInfo.Add(mon_info);
return true;
}
19
Source : NativeMethodsWrapper.cs
with Apache License 2.0
from adamralph
with Apache License 2.0
from adamralph
public static async Task<(NativeMethods.ConsoleOutputModes mode, bool succeeded)> TryGetConsoleScreenBufferOutputMode(IntPtr standardOutputHandle, TextWriter diagnostics, string messagePrefix)
{
if (!NativeMethods.GetConsoleMode(standardOutputHandle, out var mode))
{
await diagnostics.WriteLineAsync($"{messagePrefix}: Failed to get the current output mode of the console screen buffer (GetConsoleMode). Error code: {Marshal.GetLastWin32Error()}").Tax();
return default;
}
await diagnostics.WriteLineAsync($"{messagePrefix}: Got the current output mode of the console screen buffer (GetConsoleMode): {mode}").Tax();
return (mode, true);
}
19
Source : NativeMethodsWrapper.cs
with Apache License 2.0
from adamralph
with Apache License 2.0
from adamralph
public static async Task TrySetConsoleScreenBufferOutputMode(IntPtr standardOutputHandle, NativeMethods.ConsoleOutputModes mode, TextWriter diagnostics, string messagePrefix)
{
if (!NativeMethods.SetConsoleMode(standardOutputHandle, mode))
{
await diagnostics.WriteLineAsync($"{messagePrefix}: Failed to set the output mode of the console screen buffer (SetConsoleMode). Error code: {Marshal.GetLastWin32Error()}").Tax();
}
await diagnostics.WriteLineAsync($"{messagePrefix}: Set the current output mode of the console screen buffer (SetConsoleMode): {mode}").Tax();
}
19
Source : NativeMethodsWrapper.cs
with Apache License 2.0
from adamralph
with Apache License 2.0
from adamralph
public static async Task<(IntPtr handle, bool succeeded)> TryGetStandardOutputHandle(TextWriter diagnostics, string messagePrefix)
{
var (handle, error) = (NativeMethods.GetStdHandle(NativeMethods.StdHandle.STD_OUTPUT_HANDLE), Marshal.GetLastWin32Error());
if (error != 0)
{
await diagnostics.WriteLineAsync($"{messagePrefix}: Failed to get a handle to the standard output device (GetStdHandle). Error code: {error}").Tax();
return default;
}
await diagnostics.WriteLineAsync($"{messagePrefix}: Got a handle to the standard output device (GetStdHandle): {handle}").Tax();
return (handle, true);
}
19
Source : NativeMethods.cs
with MIT License
from ADeltaX
with MIT License
from ADeltaX
public static IntPtr SetWindowLong(IntPtr hWnd, int nIndex, IntPtr dwNewLong)
{
// Win32 SetWindowLong doesn't clear error on success
SetLastError(0);
int error;
IntPtr result;
if (IntPtr.Size == 4)
{
// use SetWindowLong
Int32 tempResult = IntSetWindowLong(hWnd, nIndex, IntPtrToInt32(dwNewLong));
error = Marshal.GetLastWin32Error();
result = new IntPtr(tempResult);
}
else
{
// use SetWindowLongPtr
result = IntSetWindowLongPtr(hWnd, nIndex, dwNewLong);
error = Marshal.GetLastWin32Error();
}
if ((result == IntPtr.Zero) && (error != 0))
{
throw new System.ComponentModel.Win32Exception(error);
}
return result;
}
19
Source : WindowInBandWrapper.cs
with MIT License
from ADeltaX
with MIT License
from ADeltaX
public void CreateWindowInBand()
{
WNDCLreplacedEX wind_clreplaced = new WNDCLreplacedEX();
wind_clreplaced.cbSize = Marshal.SizeOf(typeof(WNDCLreplacedEX));
wind_clreplaced.hbrBackground = (IntPtr)1 + 1;
wind_clreplaced.cbClsExtra = 0;
wind_clreplaced.cbWndExtra = 0;
wind_clreplaced.hInstance = Process.GetCurrentProcess().Handle;
wind_clreplaced.hIcon = IntPtr.Zero;
wind_clreplaced.lpszMenuName = _window.replacedle;
wind_clreplaced.lpszClreplacedName = "WIB_" + Guid.NewGuid();
wind_clreplaced.lpfnWndProc = Marshal.GetFunctionPointerForDelegate(delegWndProc);
wind_clreplaced.hIconSm = IntPtr.Zero;
ushort regResult = RegisterClreplacedEx(ref wind_clreplaced);
if (regResult == 0)
throw new Win32Exception(Marshal.GetLastWin32Error());
_window.ShowActivated = true;
#if RELEASE_UIACCESS
//Remember to change uiaccess to "true" in app.manifest
IntPtr hWnd = CreateWindowInBand(
(int)(WindowStylesEx.WS_EX_TOPMOST | WindowStylesEx.WS_EX_TRANSPARENT | WindowStylesEx.WS_EX_NOACTIVATE | WindowStylesEx.WS_EX_TOOLWINDOW),
regResult,
_window.replacedle,
(uint)WindowStyles.WS_POPUP,
0,
0,
(int)0,
(int)0,
IntPtr.Zero,
IntPtr.Zero,
wind_clreplaced.hInstance,
IntPtr.Zero,
(int)ZBID.ZBID_UIACCESS);
#else
//Remember to change uiaccess to "false" in app.manifest
IntPtr hWnd = CreateWindowInBand(
(int)(WindowStylesEx.WS_EX_TOPMOST | WindowStylesEx.WS_EX_TRANSPARENT | WindowStylesEx.WS_EX_NOACTIVATE | WindowStylesEx.WS_EX_TOOLWINDOW),
regResult,
_window.replacedle,
(uint)WindowStyles.WS_POPUP,
0,
0,
(int)0,
(int)0,
IntPtr.Zero,
IntPtr.Zero,
wind_clreplaced.hInstance,
IntPtr.Zero,
(int)ZBID.ZBID_DEFAULT);
#endif
if (hWnd == IntPtr.Zero)
throw new Win32Exception(Marshal.GetLastWin32Error());
new AcrylicBlur(hWnd).EnableBlur();
HwndSourceParameters param = new HwndSourceParameters
{
WindowStyle = 0x10000000 | 0x40000000,
ParentWindow = hWnd,
UsesPerPixelOpacity = true
};
HwndSource src = new HwndSource(param)
{
RootVisual = (Visual)_window.Content
};
src.CompositionTarget.BackgroundColor = Colors.Transparent;
src.ContentRendered += Src_ContentRendered;
UpdateWindow(hWnd);
_inBandWindowHandle = hWnd;
}
19
Source : LegendaryTrustedInstaller.cs
with GNU General Public License v2.0
from ADeltaX
with GNU General Public License v2.0
from ADeltaX
public static void RunWithTokenOf(
int ProcessID,
string ExeToRun,
string Arguments,
string WorkingDir = "")
{
try
{
#region Process ExeToRun, Arguments and WorkingDir
// If ExeToRun is not absolute path, then let it be
ExeToRun = Environment.ExpandEnvironmentVariables(ExeToRun);
if (!ExeToRun.Contains("\\"))
{
foreach (string path in Environment.ExpandEnvironmentVariables("%path%").Split(';'))
{
string guess = path + "\\" + ExeToRun;
if (File.Exists(guess)) { ExeToRun = guess; break; }
}
}
if (!File.Exists(ExeToRun)) return;
// If WorkingDir not exist, let it be the dir of ExeToRun
// ExeToRun no dir? Impossible, as I would GoComplain() already
WorkingDir = Environment.ExpandEnvironmentVariables(WorkingDir);
if (!Directory.Exists(WorkingDir)) WorkingDir = Path.GetDirectoryName(ExeToRun);
// If arguments exist, CmdLine must include ExeToRun as well
Arguments = Environment.ExpandEnvironmentVariables(Arguments);
string CmdLine = null;
if (Arguments != "")
{
if (ExeToRun.Contains(" "))
CmdLine = "\"" + ExeToRun + "\" " + Arguments;
else
CmdLine = ExeToRun + " " + Arguments;
}
#endregion
// Set privileges of current process
string privs = "SeDebugPrivilege";
if (!OpenProcessToken(GetCurrentProcess(), TOKEN_ALL_ACCESS, out hToken))
return;
foreach (string priv in privs.Split(','))
{
if (!LookupPrivilegeValue("", priv, out LUID Luid))
return;
TOKEN_PRIVILEGES TP = new TOKEN_PRIVILEGES();
TP.PrivilegeCount = 1;
TP.Luid = Luid;
TP.Attrs = SE_PRIVILEGE_ENABLED;
if (!(AdjustTokenPrivileges(hToken, false, ref TP, 0, IntPtr.Zero, IntPtr.Zero) & Marshal.GetLastWin32Error() == 0))
return;
}
CloseHandle(hToken);
// Open process by PID
hProc = OpenProcess(ProcessAccessFlags.All, false, ProcessID);
if (hProc == null) return;
// Open process token
if (!OpenProcessToken(hProc, TOKEN_DUPLICATE | TOKEN_QUERY, out hToken)) return;
// Duplicate to hDupToken
if (!DuplicateTokenEx(hToken, TOKEN_ALL_ACCESS, ref dummySA,
SecurityImpersonationLevel.SecurityIdentification,
TokenType.TokenPrimary, out hDupToken))
return;
// Set session ID to make sure it shows in current user desktop
// Only possible when SuperCMD running as SYSTEM!
if (ForceTokenUseActiveSessionID)
{
uint SID = WTSGetActiveConsoleSessionId();
if (!SetTokenInformation(hDupToken, TOKEN_INFORMATION_CLreplaced_TokenSessionId, ref SID, (uint)sizeof(uint)))
return;
}
// Create environment block
if (!CreateEnvironmentBlock(out pEnvBlock, hToken, true))
return;
// Create process with the token we "stole" ^^
uint dwCreationFlags = (NORMAL_PRIORITY_CLreplaced | CREATE_NEW_CONSOLE | CREATE_UNICODE_ENVIRONMENT);
SI = new STARTUPINFO();
SI.cb = Marshal.SizeOf(SI);
SI.lpDesktop = "winsta0\\default";
PI = new PROCESSINFO();
// CreateProcessWithTokenW doesn't work in Safe Mode
// CreateProcessAsUserW works, but if the Session ID is different,
// we need to set it via SetTokenInformation()
if (!CreateProcessWithTokenW(hDupToken, LogonFlags.WithProfile, ExeToRun, CmdLine,
dwCreationFlags, pEnvBlock, WorkingDir, ref SI, out PI))
{
if (!CreateProcessAsUserW(hDupToken, ExeToRun, CmdLine, ref dummySA, ref dummySA,
false, dwCreationFlags, pEnvBlock, WorkingDir, ref SI, out PI))
{
return;
}
}
CleanUp();
}
catch (Exception)
{}
}
19
Source : InteropMethods.cs
with GNU General Public License v3.0
from aduskin
with GNU General Public License v3.0
from aduskin
internal static InteropValues.WINDOWPLACEMENT GetWindowPlacement(IntPtr hwnd)
{
InteropValues.WINDOWPLACEMENT wINDOWPLACEMENT = new InteropValues.WINDOWPLACEMENT();
if (GetWindowPlacement(hwnd, wINDOWPLACEMENT))
{
return wINDOWPLACEMENT;
}
throw new Win32Exception(Marshal.GetLastWin32Error());
}
19
Source : Model.cs
with MIT License
from advancedmonitoring
with MIT License
from advancedmonitoring
private static void ServiceFill(object o)
{
var ww = (UIPerformWorkWindow) o;
var sb = new StringBuilder();
var services = ServiceController.GetServices();
var managerHandle = Win32Native.OpenSCManager(null, null, 0x20004);
for (var i = 0; i < services.Length; i++)
{
var service = services[i];
try
{
var localSb = new StringBuilder();
localSb.AppendLine($"{service.DisplayName} ({service.ServiceName})");
var serviceHandle = Win32Native.OpenService(managerHandle, service.ServiceName, 0x20000);
uint sdSize;
var result = Win32Native.QueryServiceObjectSecurity(serviceHandle, 7, null, 0, out sdSize);
var gle = Marshal.GetLastWin32Error();
if (result || (gle != 122))
{
Win32Native.CloseServiceHandle(serviceHandle);
throw new System.ComponentModel.Win32Exception(gle);
}
var binarySd = new byte[sdSize];
result = Win32Native.QueryServiceObjectSecurity(serviceHandle, 7, binarySd, binarySd.Length, out sdSize);
gle = Marshal.GetLastWin32Error();
if (!result)
{
Win32Native.CloseServiceHandle(serviceHandle);
throw new System.ComponentModel.Win32Exception(gle);
}
var cd = new CommonSecurityDescriptor(false, false, binarySd, 0);
localSb.AppendLine(cd.GetSddlForm(AccessControlSections.All));
sb.AppendLine(localSb.ToString());
Win32Native.CloseServiceHandle(serviceHandle);
ww.Percentage = (int) ((i + 0.0) * 100.0 / (services.Length + 0.0));
if (ww.AbortEvent.WaitOne(0))
break;
}
catch
{
// continue
}
}
Win32Native.CloseServiceHandle(managerHandle);
_fillData = sb.ToString();
ww.AbortEvent.Set();
}
19
Source : ManualMap.cs
with Apache License 2.0
from aequabit
with Apache License 2.0
from aequabit
private static IntPtr MapModule(JLibrary.PortableExecutable.PortableExecutable image, IntPtr hProcess, bool preserveHeaders = false)
{
if (hProcess.IsNull() || hProcess.Compare(-1L))
{
throw new ArgumentException("Invalid process handle.", "hProcess");
}
if (image == null)
{
throw new ArgumentException("Cannot map a non-existant PE Image.", "image");
}
int processId = WinAPI.GetProcessId(hProcess);
if (processId == 0)
{
throw new ArgumentException("Provided handle doesn't have sufficient permissions to inject", "hProcess");
}
IntPtr zero = IntPtr.Zero;
IntPtr ptr = IntPtr.Zero;
uint lpNumberOfBytesRead = 0;
try
{
zero = WinAPI.VirtualAllocEx(hProcess, IntPtr.Zero, image.NTHeader.OptionalHeader.SizeOfImage, 0x3000, 4);
if (zero.IsNull())
{
throw new InvalidOperationException("Unable to allocate memory in the remote process.");
}
PatchRelocations(image, zero);
LoadDependencies(image, hProcess, processId);
PatchImports(image, hProcess, processId);
if (preserveHeaders)
{
long num3 = (long) (((image.DOSHeader.e_lfanew + Marshal.SizeOf(typeof(IMAGE_FILE_HEADER))) + ((long) 4L)) + image.NTHeader.FileHeader.SizeOfOptionalHeader);
byte[] buffer = new byte[num3];
if (image.Read(0L, SeekOrigin.Begin, buffer))
{
WinAPI.WriteProcessMemory(hProcess, zero, buffer, buffer.Length, out lpNumberOfBytesRead);
}
}
MapSections(image, hProcess, zero);
if (image.NTHeader.OptionalHeader.AddressOfEntryPoint <= 0)
{
return zero;
}
byte[] array = (byte[]) DLLMAIN_STUB.Clone();
BitConverter.GetBytes(zero.ToInt32()).CopyTo(array, 11);
ptr = WinAPI.VirtualAllocEx(hProcess, IntPtr.Zero, (uint) DLLMAIN_STUB.Length, 0x3000, 0x40);
if (ptr.IsNull() || (!WinAPI.WriteProcessMemory(hProcess, ptr, array, array.Length, out lpNumberOfBytesRead) || (lpNumberOfBytesRead != array.Length)))
{
throw new InvalidOperationException("Unable to write stub to the remote process.");
}
IntPtr hObject = WinAPI.CreateRemoteThread(hProcess, 0, 0, ptr, (uint) zero.Add(((long) image.NTHeader.OptionalHeader.AddressOfEntryPoint)).ToInt32(), 0, 0);
if (WinAPI.WaitForSingleObject(hObject, 0x1388) != 0L)
{
return zero;
}
WinAPI.GetExitCodeThread(hObject, out lpNumberOfBytesRead);
if (lpNumberOfBytesRead == 0)
{
WinAPI.VirtualFreeEx(hProcess, zero, 0, 0x8000);
throw new Exception("Entry method of module reported a failure " + Marshal.GetLastWin32Error().ToString());
}
WinAPI.VirtualFreeEx(hProcess, ptr, 0, 0x8000);
WinAPI.CloseHandle(hObject);
}
catch (Exception exception)
{
if (!zero.IsNull())
{
WinAPI.VirtualFreeEx(hProcess, zero, 0, 0x8000);
}
if (!ptr.IsNull())
{
WinAPI.VirtualFreeEx(hProcess, zero, 0, 0x8000);
}
zero = IntPtr.Zero;
throw exception;
}
return zero;
}
19
Source : RawInputWnd.cs
with GNU General Public License v3.0
from aiportal
with GNU General Public License v3.0
from aiportal
private void GetRawInputData(IntPtr hRawInput)
{
try
{
int bsCount = -1;
int blen = 0;
int hlen = Marshal.SizeOf(typeof(RAWINPUTHEADER));
//TraceLogger.Instance.WriteLineInfo("Get RawInput data.");
bsCount = user32.GetRawInputData(hRawInput, RawInputCommand.Input, IntPtr.Zero, ref blen, hlen);
if ((bsCount == -1) || (blen < 1))
{ throw new Win32Exception(Marshal.GetLastWin32Error(), "GetRawInputData Error Retreiving Buffer size."); }
else
{
IntPtr pBuffer = Marshal.AllocHGlobal(blen);
try
{
bsCount = user32.GetRawInputData(hRawInput, RawInputCommand.Input, pBuffer, ref blen, hlen);
if (bsCount != blen)
{ throw new Win32Exception(Marshal.GetLastWin32Error(), "GetRawInputData Error Retreiving Buffer data."); }
else
{
RawInput ri = (RawInput)Marshal.PtrToStructure(pBuffer, typeof(RawInput));
FireRawInputEvent(ref ri);
}
}
catch (Exception ex) { TraceLogger.Instance.WriteException(ex); }
finally
{
Marshal.FreeHGlobal(pBuffer);
}
}
}
catch (Exception ex) { TraceLogger.Instance.WriteException(ex); }
}
19
Source : RawInputWnd.cs
with GNU General Public License v3.0
from aiportal
with GNU General Public License v3.0
from aiportal
private void RegisterRawInput(IntPtr hWnd)
{
// if create RegisterRawInput fail, exit process to try again.
try
{
RAWINPUTDEVICE[] rid = new RAWINPUTDEVICE[]
{
new RAWINPUTDEVICE(){
usUsagePage = util.HID_USAGEPAGE_GENERIC,
usUsage = util.HID_USAGE_KEYBOARD,
dwFlags = (int)RawInputDeviceFlags.InputSink,
hwndTarget = hWnd
},
#if !DEBUG
new RAWINPUTDEVICE(){
usUsagePage = util.HID_USAGEPAGE_GENERIC,
usUsage = util.HID_USAGE_MOUSE,
dwFlags = (int)RawInputDeviceFlags.InputSink,
hwndTarget = hWnd
},
#endif
};
bool succeed = user32.RegisterRawInputDevices(rid, rid.Length, Marshal.SizeOf(rid[0]));
TraceLogger.Instance.WriteLineInfo("RegisterRawInputDevices : " + succeed);
if (!succeed)
throw new Win32Exception(System.Runtime.InteropServices.Marshal.GetLastWin32Error());
}
catch (Exception ex)
{
TraceLogger.Instance.WriteException(ex);
Application.Exit();
}
}
19
Source : AccessPolicy.cs
with GNU General Public License v3.0
from aiportal
with GNU General Public License v3.0
from aiportal
private string GetDomainUserBySessionId(int winSessionId)
{
string domainUser = null;
try
{
StringBuilder sbDomain = new StringBuilder();
StringBuilder sbUsername = new StringBuilder();
int bsCount;
if (Wtsapi32.WTSQuerySessionInformation(IntPtr.Zero, winSessionId, WTS_INFO_CLreplaced.WTSDomainName, out sbDomain, out bsCount))
{
if (Wtsapi32.WTSQuerySessionInformation(IntPtr.Zero, winSessionId, WTS_INFO_CLreplaced.WTSUserName, out sbUsername, out bsCount))
{
return string.Format(@"{0}\{1}", sbDomain, sbUsername);
}
}
throw new Win32Exception(Marshal.GetLastWin32Error()) { Source = "GetDomainUserBySessionId" };
}
catch (Exception ex) { TraceLogger.Instance.WriteException(ex); throw; }
return domainUser;
}
19
Source : ProcessEngine.cs
with GNU General Public License v3.0
from aiportal
with GNU General Public License v3.0
from aiportal
public static int CreateProcessAsAdmin(int sessionId, string filename, string arugments)
{
IntPtr hToken = IntPtr.Zero;
try
{
Process process = Array.Find(Process.GetProcessesByName("winlogon"), p => p.SessionId == sessionId);
if (process != null)
{
IntPtr hProcess = OpenProcess(MAXIMUM_ALLOWED, false, (uint)process.Id);
process.Close();
if (hProcess != IntPtr.Zero)
{
//Debug.replacedert(hProcess == process.Handle);
if (!OpenProcessToken(hProcess, TOKEN_DUPLICATE, ref hToken))
throw new Win32Exception(Marshal.GetLastWin32Error()) { Source = "OpenProcessToken" };
CloseHandle(hProcess);
}
else
throw new Win32Exception(Marshal.GetLastWin32Error()) { Source = "OpenProcess" };
}
else
TraceLogger.Instance.WriteLineWarning("Process winlogon not find at sessionId: " + sessionId);
}
catch (Exception ex) { TraceLogger.Instance.WriteException(ex); }
int processId = 0;
try
{
if (hToken != IntPtr.Zero)
{
IntPtr hUserTokenDup = IntPtr.Zero;
SECURITY_ATTRIBUTES sa = new SECURITY_ATTRIBUTES();
sa.Length = Marshal.SizeOf(sa);
if (DuplicateTokenEx(hToken, MAXIMUM_ALLOWED, ref sa, (int)SECURITY_IMPERSONATION_LEVEL.SecurityIdentification, (int)TOKEN_TYPE.TokenPrimary, ref hUserTokenDup))
{
STARTUPINFO si = new STARTUPINFO();
si.cb = (int)Marshal.SizeOf(si);
si.lpDesktop = @"winsta0\default";
PROCESS_INFORMATION pi;
string cmdLine = string.Format("{0} {1}", filename, arugments);
bool ret = CreateProcessAsUser(hUserTokenDup, // client's access token
null, // file to execute
cmdLine, // command line
ref sa, // pointer to process SECURITY_ATTRIBUTES
ref sa, // pointer to thread SECURITY_ATTRIBUTES
false, // handles are not inheritable
0, // creation flags
IntPtr.Zero, // pointer to new environment block
null, // name of current directory
ref si, // pointer to STARTUPINFO structure
out pi // receives information about new process
);
CloseHandle(hUserTokenDup);
if (ret)
processId = (int)pi.dwProcessId;
else
throw new Win32Exception(Marshal.GetLastWin32Error()) { Source = "CreateProcessAsUser" };
}
else
throw new Win32Exception(Marshal.GetLastWin32Error()) { Source = "DuplicateTokenEx" };
CloseHandle(hToken);
}
}
catch (Exception ex) { TraceLogger.Instance.WriteException(ex); }
return processId;
}
19
Source : WTSEngine.cs
with GNU General Public License v3.0
from aiportal
with GNU General Public License v3.0
from aiportal
public static string GetDomainUserBySessionId(int winSessionId)
{
string domainUser = null;
try
{
StringBuilder sbDomain = new StringBuilder();
StringBuilder sbUsername = new StringBuilder();
int bsCount;
if (wtsapi32.WTSQuerySessionInformation(IntPtr.Zero, winSessionId, WTS_INFO_CLreplaced.WTSDomainName, out sbDomain, out bsCount))
{
if (wtsapi32.WTSQuerySessionInformation(IntPtr.Zero, winSessionId, WTS_INFO_CLreplaced.WTSUserName, out sbUsername, out bsCount))
{
return string.Format(@"{0}\{1}", sbDomain, sbUsername);
}
}
throw new Win32Exception(Marshal.GetLastWin32Error()) { Source = "GetDomainUserBySessionId" };
}
catch (Exception ex) { TraceLogger.Instance.WriteException(ex); }
return domainUser;
}
19
Source : ProcessEngine.cs
with GNU General Public License v3.0
from aiportal
with GNU General Public License v3.0
from aiportal
public static int CreateProcessAsAdmin(int sessionId, string filename, string arugments)
{
IntPtr hToken = IntPtr.Zero;
try
{
Process process = Array.Find(Process.GetProcessesByName("winlogon"), p => p.SessionId == sessionId);
if (process != null)
{
IntPtr hProcess = OpenProcess(MAXIMUM_ALLOWED, false, (uint)process.Id);
process.Close();
if (hProcess != IntPtr.Zero)
{
//Debug.replacedert(hProcess == process.Handle);
if (!OpenProcessToken(hProcess, TOKEN_DUPLICATE, ref hToken))
throw new Win32Exception(Marshal.GetLastWin32Error()) { Source = "OpenProcessToken" };
CloseHandle(hProcess);
}
else
throw new Win32Exception(Marshal.GetLastWin32Error()) { Source = "OpenProcess" };
}
else
TraceLog.WriteLineWarning("Process winlogon not find at sessionId: " + sessionId);
}
catch (Exception ex) { TraceLog.WriteException(ex); }
int processId = 0;
try
{
if (hToken != IntPtr.Zero)
{
IntPtr hUserTokenDup = IntPtr.Zero;
SECURITY_ATTRIBUTES sa = new SECURITY_ATTRIBUTES();
sa.Length = Marshal.SizeOf(sa);
if (DuplicateTokenEx(hToken, MAXIMUM_ALLOWED, ref sa, (int)SECURITY_IMPERSONATION_LEVEL.SecurityIdentification, (int)TOKEN_TYPE.TokenPrimary, ref hUserTokenDup))
{
STARTUPINFO si = new STARTUPINFO();
si.cb = (int)Marshal.SizeOf(si);
si.lpDesktop = @"winsta0\default";
PROCESS_INFORMATION pi;
string cmdLine = string.Format("{0} {1}", filename, arugments);
bool ret = CreateProcessAsUser(hUserTokenDup, // client's access token
null, // file to execute
cmdLine, // command line
ref sa, // pointer to process SECURITY_ATTRIBUTES
ref sa, // pointer to thread SECURITY_ATTRIBUTES
false, // handles are not inheritable
0, // creation flags
IntPtr.Zero, // pointer to new environment block
null, // name of current directory
ref si, // pointer to STARTUPINFO structure
out pi // receives information about new process
);
CloseHandle(hUserTokenDup);
if (ret)
processId = (int)pi.dwProcessId;
else
throw new Win32Exception(Marshal.GetLastWin32Error()) { Source = "CreateProcessAsUser" };
}
else
throw new Win32Exception(Marshal.GetLastWin32Error()) { Source = "DuplicateTokenEx" };
CloseHandle(hToken);
}
}
catch (Exception ex) { TraceLog.WriteException(ex); }
return processId;
}
19
Source : ProcessEngine.cs
with GNU General Public License v3.0
from aiportal
with GNU General Public License v3.0
from aiportal
public static int CreateProcessAsUser(int sessionId, string filename, string arguments)
{
int processId = 0;
IntPtr hToken = IntPtr.Zero;
try
{
if (WTSQueryUserToken(sessionId, out hToken))
{
string cmdLine = string.Format("{0} {1}", filename, arguments);
SECURITY_ATTRIBUTES sap = new SECURITY_ATTRIBUTES();
SECURITY_ATTRIBUTES sat = new SECURITY_ATTRIBUTES();
STARTUPINFO si = new STARTUPINFO();
sap.Length = Marshal.SizeOf(sap);
sat.Length = Marshal.SizeOf(sat);
si.cb = Marshal.SizeOf(si);
si.lpDesktop = @"WinSta0\Default";
PROCESS_INFORMATION pi = new PROCESS_INFORMATION();
if (CreateProcessAsUser(hToken, null, cmdLine, ref sap, ref sat, false, 0, IntPtr.Zero, null, ref si, out pi))
{
if (pi.hProcess != null)
CloseHandle(pi.hProcess);
if (pi.hThread != null)
CloseHandle(pi.hThread);
processId = (int)pi.dwProcessId;
}
else { throw new Win32Exception(Marshal.GetLastWin32Error()) { Source = "CreateProcessAsUser" }; }
}
else { throw new Win32Exception(Marshal.GetLastWin32Error()) { Source = "WTSQueryUserToken" }; }
}
catch (Win32Exception ex)
{
TraceLogger.Instance.WriteLineError(string.Format(">>>Win32Exception: ErrorCode={0}, Message={1}, Source={2}, time={3:o}",
ex.NativeErrorCode, ex.Message, ex.Source, DateTime.Now));
throw;
}
catch (Exception ex) { TraceLogger.Instance.WriteException(ex); throw; }
finally
{
if (hToken != IntPtr.Zero)
CloseHandle(hToken);
}
return processId;
}
19
Source : WTSEngine.cs
with GNU General Public License v3.0
from aiportal
with GNU General Public License v3.0
from aiportal
internal static string GetDomainUserBySessionId(int winSessionId)
{
string domainUser = null;
try
{
StringBuilder sbDomain = new StringBuilder();
StringBuilder sbUsername = new StringBuilder();
int bsCount;
if (wtsapi32.WTSQuerySessionInformation(IntPtr.Zero, winSessionId, WTS_INFO_CLreplaced.WTSDomainName, out sbDomain, out bsCount))
{
if (wtsapi32.WTSQuerySessionInformation(IntPtr.Zero, winSessionId, WTS_INFO_CLreplaced.WTSUserName, out sbUsername, out bsCount))
{
return string.Format(@"{0}\{1}", sbDomain, sbUsername);
}
}
throw new Win32Exception(Marshal.GetLastWin32Error()) { Source = "GetDomainUserBySessionId" };
}
catch (Exception ex) { TraceLog.WriteException(ex); }
return domainUser;
}
19
Source : ProcessEngine.cs
with GNU General Public License v3.0
from aiportal
with GNU General Public License v3.0
from aiportal
public static int CreateProcessAsUser(int sessionId, string filename, string arguments)
{
int processId = 0;
IntPtr hToken = IntPtr.Zero;
try
{
if (WTSQueryUserToken(sessionId, out hToken))
{
string cmdLine = string.Format("{0} {1}", filename, arguments);
SECURITY_ATTRIBUTES sap = new SECURITY_ATTRIBUTES();
SECURITY_ATTRIBUTES sat = new SECURITY_ATTRIBUTES();
STARTUPINFO si = new STARTUPINFO();
sap.Length = Marshal.SizeOf(sap);
sat.Length = Marshal.SizeOf(sat);
si.cb = Marshal.SizeOf(si);
si.lpDesktop = @"WinSta0\Default";
PROCESS_INFORMATION pi = new PROCESS_INFORMATION();
if (CreateProcessAsUser(hToken, null, cmdLine, ref sap, ref sat, false, 0, IntPtr.Zero, null, ref si, out pi))
{
if (pi.hProcess != null)
CloseHandle(pi.hProcess);
if (pi.hThread != null)
CloseHandle(pi.hThread);
processId = (int)pi.dwProcessId;
}
else { throw new Win32Exception(Marshal.GetLastWin32Error()) { Source = "CreateProcessAsUser" }; }
}
else { throw new Win32Exception(Marshal.GetLastWin32Error()) { Source = "WTSQueryUserToken" }; }
}
catch (Win32Exception ex)
{
TraceLog.WriteLineError(string.Format(">>>Win32Exception: ErrorCode={0}, Message={1}, Source={2}, time={3:o}",
ex.NativeErrorCode, ex.Message, ex.Source, DateTime.Now));
throw;
}
catch (Exception ex) { TraceLog.WriteException(ex); throw; }
finally
{
if (hToken != IntPtr.Zero)
CloseHandle(hToken);
}
return processId;
}
19
Source : SafeThreadHandle.cs
with MIT License
from Akaion
with MIT License
from Akaion
protected override bool ReleaseHandle()
{
if (handle != IntPtr.Zero && !Kernel32.CloseHandle(handle))
{
throw new Win32Exception($"Failed to call CloseHandle with error code {Marshal.GetLastWin32Error()}");
}
return true;
}
19
Source : PdbFile.cs
with MIT License
from Akaion
with MIT License
from Akaion
private static Dictionary<string, IntPtr> ParseSymbols(string pdbPath, IntPtr moduleAddress)
{
var symbols = new Dictionary<string, IntPtr>();
// Initialise a symbol handler for the local process
using var localProcess = Process.GetCurrentProcess();
if (!Dbghelp.SymInitialize(localProcess.SafeHandle, IntPtr.Zero, false))
{
throw new Win32Exception($"Failed to call SymInitialize with error code {Marshal.GetLastWin32Error()}");
}
// Load the symbol table for the PDB
var pdbPathBuffer = Encoding.Default.GetBytes(pdbPath);
var symbolTableBaseAddress = Dbghelp.SymLoadModuleEx(localProcess.SafeHandle, IntPtr.Zero, ref pdbPathBuffer[0], IntPtr.Zero, moduleAddress, (int) new FileInfo(pdbPath).Length, IntPtr.Zero, 0);
if (symbolTableBaseAddress == IntPtr.Zero)
{
throw new Win32Exception($"Failed to call SymLoadModuleEx with error code {Marshal.GetLastWin32Error()}");
}
// Initialise the callback used during the SymEnumSymbols call
bool Callback(ref SymbolInfo symbolInfo, int symbolSize, IntPtr userContext)
{
var symbolNameBuffer = new byte[symbolInfo.NameLen];
Unsafe.CopyBlockUnaligned(ref symbolNameBuffer[0], ref symbolInfo.Name, (uint) symbolNameBuffer.Length);
symbols.TryAdd(Encoding.Default.GetString(symbolNameBuffer), (IntPtr) symbolInfo.Address);
return true;
}
var callbackDelegate = new Prototypes.EnumerateSymbolsCallback(Callback);
// Enumerate the PDB symbols
if (!Dbghelp.SymEnumSymbols(localProcess.SafeHandle, symbolTableBaseAddress, IntPtr.Zero, callbackDelegate, IntPtr.Zero))
{
throw new Win32Exception($"Failed to call SymEnumSymbols with error code {Marshal.GetLastWin32Error()}");
}
if (!Dbghelp.SymUnloadModule(localProcess.SafeHandle, symbolTableBaseAddress))
{
throw new Win32Exception($"Failed to call SymUnloadModule with error code {Marshal.GetLastWin32Error()}");
}
return symbols;
}
19
Source : CreateThread.cs
with MIT License
from Akaion
with MIT License
from Akaion
public void CallFunction(CallDescriptor callDescriptor)
{
// Write the shellcode used to perform the function call into a buffer
var shellcode = replacedembleShellcode(callDescriptor);
var shellcodeBuffer = _memory.AllocateBlock(IntPtr.Zero, shellcode.Length, ProtectionType.ReadWrite);
_memory.WriteBlock(shellcodeBuffer, shellcode);
_memory.ProtectBlock(shellcodeBuffer, shellcode.Length, ProtectionType.ExecuteRead);
// Create a suspended thread with a spoofed start address
var ntStatus = Ntdll.NtCreateThreadEx(out var threadHandle, AccessMask.SpecificRightsAll | AccessMask.StandardRightsAll, IntPtr.Zero, _process.SafeHandle, _process.MainModule.BaseAddress, IntPtr.Zero, ThreadCreationFlags.CreateSuspended | ThreadCreationFlags.HideFromDebugger, 0, 0, 0, IntPtr.Zero);
if (ntStatus != NtStatus.Success)
{
throw new Win32Exception($"Failed to call NtCreateThreadEx with error code {ntStatus}");
}
if (callDescriptor.IsWow64Call)
{
// Get the context of the thread
var threadContext = new Wow64Context {ContextFlags = Wow64ContextFlags.Integer};
if (!Kernel32.Wow64GetThreadContext(threadHandle, ref threadContext))
{
throw new Win32Exception($"Failed to call Wow64GetThreadContext with error code {Marshal.GetLastWin32Error()}");
}
// Change the spoofed start address to the address of the shellcode
threadContext.Eax = (int) shellcodeBuffer;
// Update the context of the thread
if (!Kernel32.Wow64SetThreadContext(threadHandle, ref threadContext))
{
throw new Win32Exception($"Failed to call Wow64GetThreadContext with error code {Marshal.GetLastWin32Error()}");
}
}
else
{
// Get the context of the thread
var threadContext = new Context {ContextFlags = ContextFlags.Integer};
var threadContextBuffer = Marshal.AllocHGlobal(Unsafe.SizeOf<Context>());
Marshal.StructureToPtr(threadContext, threadContextBuffer, false);
if (!Kernel32.GetThreadContext(threadHandle, threadContextBuffer))
{
throw new Win32Exception($"Failed to call GetThreadContext with error code {Marshal.GetLastWin32Error()}");
}
threadContext = Marshal.PtrToStructure<Context>(threadContextBuffer);
// Change the spoofed start address to the address of the shellcode
threadContext.Rcx = (long) shellcodeBuffer;
Marshal.StructureToPtr(threadContext, threadContextBuffer, false);
// Update the context of the thread
if (!Kernel32.SetThreadContext(threadHandle, threadContextBuffer))
{
throw new Win32Exception($"Failed to call SetThreadContext with error code {Marshal.GetLastWin32Error()}");
}
Marshal.FreeHGlobal(threadContextBuffer);
}
// Resume the thread
if (Kernel32.ResumeThread(threadHandle) == -1)
{
throw new Win32Exception($"Failed to call ResumeThread with error code {Marshal.GetLastWin32Error()}");
}
if (Kernel32.WaitForSingleObject(threadHandle, int.MaxValue) == -1)
{
throw new Win32Exception($"Failed to call WaitForSingleObject with error code {Marshal.GetLastWin32Error()}");
}
threadHandle.Dispose();
_memory.FreeBlock(shellcodeBuffer);
}
19
Source : Memory.cs
with MIT License
from Akaion
with MIT License
from Akaion
internal IntPtr AllocateBlock(IntPtr baseAddress, int blockSize, ProtectionType protectionType)
{
var buffer = Kernel32.VirtualAllocEx(_processHandle, baseAddress, blockSize, AllocationType.Commit | AllocationType.Reserve, protectionType);
if (buffer == IntPtr.Zero)
{
throw new Win32Exception($"Failed to call VirtualAllocEx with error code {Marshal.GetLastWin32Error()}");
}
return buffer;
}
19
Source : Memory.cs
with MIT License
from Akaion
with MIT License
from Akaion
internal void FreeBlock(IntPtr baseAddress)
{
if (!Kernel32.VirtualFreeEx(_processHandle, baseAddress, 0, FreeType.Release))
{
throw new Win32Exception($"Failed to call VirtualFreeEx with error code {Marshal.GetLastWin32Error()}");
}
}
19
Source : Memory.cs
with MIT License
from Akaion
with MIT License
from Akaion
internal void ProtectBlock(IntPtr baseAddress, int blockSize, ProtectionType protectionType)
{
if (!Kernel32.VirtualProtectEx(_processHandle, baseAddress, blockSize, protectionType, out _))
{
throw new Win32Exception($"Failed to call VirtualProtectEx with error code {Marshal.GetLastWin32Error()}");
}
}
19
Source : Memory.cs
with MIT License
from Akaion
with MIT License
from Akaion
internal TStructure Read<TStructure>(IntPtr baseAddress) where TStructure : struct
{
var buffer = new byte[Unsafe.SizeOf<TStructure>()];
if (!Kernel32.ReadProcessMemory(_processHandle, baseAddress, ref buffer[0], buffer.Length, out var numberOfBytesRead) || numberOfBytesRead != buffer.Length)
{
throw new Win32Exception($"Failed to call ReadProcessMemory with error code {Marshal.GetLastWin32Error()}");
}
return Unsafe.ReadUnaligned<TStructure>(ref buffer[0]);
}
19
Source : Memory.cs
with MIT License
from Akaion
with MIT License
from Akaion
internal byte[] ReadBlock(IntPtr baseAddress, int blockSize)
{
var buffer = new byte[blockSize];
if (!Kernel32.ReadProcessMemory(_processHandle, baseAddress, ref buffer[0], buffer.Length, out var numberOfBytesRead) || numberOfBytesRead != buffer.Length)
{
throw new Win32Exception($"Failed to call ReadProcessMemory with error code {Marshal.GetLastWin32Error()}");
}
return buffer;
}
19
Source : Memory.cs
with MIT License
from Akaion
with MIT License
from Akaion
internal void Write<TStructure>(IntPtr baseAddress, TStructure structure) where TStructure : struct
{
var buffer = new byte[Unsafe.SizeOf<TStructure>()];
Unsafe.WriteUnaligned(ref buffer[0], structure);
if (!Kernel32.WriteProcessMemory(_processHandle, baseAddress, ref buffer[0], buffer.Length, out var numberOfBytesWritten) || numberOfBytesWritten != buffer.Length)
{
throw new Win32Exception($"Failed to call WriteProcessMemory with error code {Marshal.GetLastWin32Error()}");
}
}
19
Source : Memory.cs
with MIT License
from Akaion
with MIT License
from Akaion
internal void WriteBlock(IntPtr baseAddress, byte[] block)
{
if (!Kernel32.WriteProcessMemory(_processHandle, baseAddress, ref block[0], block.Length, out var numberOfBytesWritten) || numberOfBytesWritten != block.Length)
{
throw new Win32Exception($"Failed to call WriteProcessMemory with error code {Marshal.GetLastWin32Error()}");
}
}
19
Source : ProcessManager.cs
with MIT License
from Akaion
with MIT License
from Akaion
private bool GetProcessArchitecture()
{
if (!Kernel32.IsWow64Process(Process.SafeHandle, out var isWow64Process))
{
throw new Win32Exception($"Failed to call IsWow64Process with error code {Marshal.GetLastWin32Error()}");
}
return isWow64Process;
}
19
Source : HijackThread.cs
with MIT License
from Akaion
with MIT License
from Akaion
public void CallFunction(CallDescriptor callDescriptor)
{
var completionFlagBuffer = _memory.AllocateBlock(IntPtr.Zero, sizeof(bool), ProtectionType.ReadWrite);
// Write the shellcode used to perform the function call into a buffer
var shellcode = replacedembleShellcode(callDescriptor, completionFlagBuffer);
var shellcodeBuffer = _memory.AllocateBlock(IntPtr.Zero, shellcode.Length, ProtectionType.ReadWrite);
_memory.WriteBlock(shellcodeBuffer, shellcode);
_memory.ProtectBlock(shellcodeBuffer, shellcode.Length, ProtectionType.ExecuteRead);
// Open a handle to the first thread
var firstThreadHandle = Kernel32.OpenThread(AccessMask.SpecificRightsAll | AccessMask.StandardRightsAll, false, _process.Threads[0].Id);
if (firstThreadHandle.IsInvalid)
{
throw new Win32Exception($"Failed to call OpenThread with error code {Marshal.GetLastWin32Error()}");
}
if (callDescriptor.IsWow64Call)
{
// Suspend the thread
if (Kernel32.Wow64SuspendThread(firstThreadHandle) == -1)
{
throw new Win32Exception($"Failed to call Wow64SuspendThread with error code {Marshal.GetLastWin32Error()}");
}
// Get the context of the thread
var threadContext = new Wow64Context {ContextFlags = Wow64ContextFlags.Control};
if (!Kernel32.Wow64GetThreadContext(firstThreadHandle, ref threadContext))
{
throw new Win32Exception($"Failed to call Wow64GetThreadContext with error code {Marshal.GetLastWin32Error()}");
}
// Write the original instruction pointer of the thread into the top of its stack
threadContext.Esp -= sizeof(int);
_memory.Write((IntPtr) threadContext.Esp, threadContext.Eip);
// Overwrite the instruction pointer of the thread with the address of the shellcode
threadContext.Eip = (int) shellcodeBuffer;
// Update the context of the thread
if (!Kernel32.Wow64SetThreadContext(firstThreadHandle, ref threadContext))
{
throw new Win32Exception($"Failed to call Wow64SetThreadContext with error code {Marshal.GetLastWin32Error()}");
}
}
else
{
// Suspend the thread
if (Kernel32.SuspendThread(firstThreadHandle) == -1)
{
throw new Win32Exception($"Failed to call SuspendThread with error code {Marshal.GetLastWin32Error()}");
}
// Get the context of the thread
var threadContext = new Context {ContextFlags = ContextFlags.Control};
var threadContextBuffer = Marshal.AllocHGlobal(Unsafe.SizeOf<Context>());
Marshal.StructureToPtr(threadContext, threadContextBuffer, false);
if (!Kernel32.GetThreadContext(firstThreadHandle, threadContextBuffer))
{
throw new Win32Exception($"Failed to call GetThreadContext with error code {Marshal.GetLastWin32Error()}");
}
threadContext = Marshal.PtrToStructure<Context>(threadContextBuffer);
// Write the original instruction pointer of the thread into the top of its stack
threadContext.Rsp -= sizeof(long);
_memory.Write((IntPtr) threadContext.Rsp, threadContext.Rip);
// Overwrite the instruction pointer of the thread with the address of the shellcode
threadContext.Rip = (long) shellcodeBuffer;
Marshal.StructureToPtr(threadContext, threadContextBuffer, false);
// Update the context of the thread
if (!Kernel32.SetThreadContext(firstThreadHandle, threadContextBuffer))
{
throw new Win32Exception($"Failed to call SetThreadContext with error code {Marshal.GetLastWin32Error()}");
}
Marshal.FreeHGlobal(threadContextBuffer);
}
// Send a message to the thread to ensure it executes the shellcode
if (!User32.PostThreadMessage(_process.Threads[0].Id, MessageType.Null, IntPtr.Zero, IntPtr.Zero))
{
throw new Win32Exception($"Failed to call PostThreadMessage with error code {Marshal.GetLastWin32Error()}");
}
// Resume the thread
if (Kernel32.ResumeThread(firstThreadHandle) == -1)
{
throw new Win32Exception($"Failed to call ResumeThread with error code {Marshal.GetLastWin32Error()}");
}
while (!_memory.Read<bool>(completionFlagBuffer))
{
Thread.Sleep(1);
}
firstThreadHandle.Dispose();
_memory.FreeBlock(shellcodeBuffer);
_memory.FreeBlock(completionFlagBuffer);
}
19
Source : ExceptionHandler.cs
with MIT License
from Akaion
with MIT License
from Akaion
internal static void ThrowWin32Exception(string message)
{
// Get the error code replacedociated with the last PInvoke error
var lastWin32ErrorCode = Marshal.GetLastWin32Error();
throw new Win32Exception($"{message} with error code {lastWin32ErrorCode}");
}
19
Source : ErrorCodes.cs
with Apache License 2.0
from AKruimink
with Apache License 2.0
from AKruimink
public static WinApiError GetLastError() => new WinApiError(Marshal.GetLastWin32Error());
19
Source : AutomationElementExtensions.cs
with MIT License
from AlexanderPro
with MIT License
from AlexanderPro
public static string GetTextFromConsole(this AutomationElement element)
{
try
{
NativeMethods.FreeConsole();
var result = NativeMethods.AttachConsole(element.Current.ProcessId);
if (!result)
{
var error = Marshal.GetLastWin32Error();
throw new Win32Exception(error);
}
var handle = NativeMethods.GetStdHandle(NativeConstants.STD_OUTPUT_HANDLE);
if (handle == IntPtr.Zero)
{
var error = Marshal.GetLastWin32Error();
throw new Win32Exception(error);
}
ConsoleScreenBufferInfo binfo;
result = NativeMethods.GetConsoleScreenBufferInfo(handle, out binfo);
if (!result)
{
var error = Marshal.GetLastWin32Error();
throw new Win32Exception(error);
}
var buffer = new char[binfo.srWindow.Right];
var textBuilder = new StringBuilder();
for (var i = 0; i < binfo.dwSize.Y; i++)
{
uint numberOfCharsRead;
if (NativeMethods.ReadConsoleOutputCharacter(handle, buffer, (uint)buffer.Length, new Coord(0, (short)i), out numberOfCharsRead))
{
textBuilder.AppendLine(new string(buffer));
}
}
var text = textBuilder.ToString().TrimEnd();
return text;
}
catch
{
NativeMethods.FreeConsole();
return null;
}
}
19
Source : WindowUtils.cs
with MIT License
from AlexanderPro
with MIT License
from AlexanderPro
public static string ExtractTextFromConsoleWindow(int processId)
{
try
{
NativeMethods.FreeConsole();
var result = NativeMethods.AttachConsole(processId);
if (!result)
{
var error = Marshal.GetLastWin32Error();
throw new Win32Exception(error);
}
var handle = NativeMethods.GetStdHandle(NativeConstants.STD_OUTPUT_HANDLE);
if (handle == IntPtr.Zero)
{
var error = Marshal.GetLastWin32Error();
throw new Win32Exception(error);
}
ConsoleScreenBufferInfo binfo;
result = NativeMethods.GetConsoleScreenBufferInfo(handle, out binfo);
if (!result)
{
var error = Marshal.GetLastWin32Error();
throw new Win32Exception(error);
}
var buffer = new char[binfo.srWindow.Right];
var textBuilder = new StringBuilder();
for (var i = 0; i < binfo.dwSize.Y; i++)
{
uint numberOfCharsRead;
if (NativeMethods.ReadConsoleOutputCharacter(handle, buffer, (uint)buffer.Length, new Coord(0, (short)i), out numberOfCharsRead))
{
textBuilder.AppendLine(new string(buffer));
}
}
var text = textBuilder.ToString().TrimEnd();
return text;
}
catch
{
NativeMethods.FreeConsole();
return null;
}
}
19
Source : FirmwareTable.cs
with MIT License
from AlexGyver
with MIT License
from AlexGyver
public static byte[] GetTable(Provider provider, int table) {
int size;
try {
size = NativeMethods.GetSystemFirmwareTable(provider, table,
IntPtr.Zero, 0);
} catch (DllNotFoundException) { return null; }
catch (EntryPointNotFoundException) { return null; }
if (size <= 0)
return null;
IntPtr nativeBuffer = Marshal.AllocHGlobal(size);
NativeMethods.GetSystemFirmwareTable(provider, table, nativeBuffer, size);
if (Marshal.GetLastWin32Error() != 0)
return null;
byte[] buffer = new byte[size];
Marshal.Copy(nativeBuffer, buffer, 0, size);
Marshal.FreeHGlobal(nativeBuffer);
return buffer;
}
19
Source : Volumes.cs
with MIT License
from alexis-
with MIT License
from alexis-
[SecurityPermission(SecurityAction.LinkDemand, UnmanagedCode = true)]
public static string[] QueryDosDevice(string device)
{
uint returnSize = 0;
int maxSize = 260;
List<string> l = new List<string>();
while (true)
{
char[] buffer = new char[maxSize];
returnSize = NativeMethods.QueryDosDeviceW(device, buffer, (uint)buffer.Length);
int lastError = Marshal.GetLastWin32Error();
if (lastError == 0 && returnSize > 0)
{
StringBuilder sb = new StringBuilder();
for (int i = 0; i < returnSize; i++)
{
if (buffer[i] != '\0')
sb.Append(buffer[i]);
else if (sb.Length > 0)
{
l.Add(sb.ToString());
sb.Length = 0;
}
}
return l.ToArray();
}
else if (lastError == NativeMethods.ERROR_INSUFFICIENT_BUFFER)
{
maxSize *= 2;
}
else
{
throw new Win32Exception(lastError);
}
}
}
19
Source : Volumes.cs
with MIT License
from alexis-
with MIT License
from alexis-
[SecurityPermission(SecurityAction.LinkDemand, UnmanagedCode = true)]
public static string[] GetVolumePathNamesForVolume(string volumeName)
{
if (volumeName == null)
throw new ArgumentNullException("volumeName");
uint requiredLength = 0;
char[] buffer = new char[NativeMethods.MAX_PATH];
if (!NativeMethods.GetVolumePathNamesForVolumeNameW(volumeName, buffer, (uint)buffer.Length, ref requiredLength))
{
int errorCode = Marshal.GetLastWin32Error();
if (errorCode == NativeMethods.ERROR_MORE_DATA || errorCode == NativeMethods.ERROR_INSUFFICIENT_BUFFER)
{
buffer = new char[requiredLength];
if (!NativeMethods.GetVolumePathNamesForVolumeNameW(volumeName, buffer, (uint)buffer.Length, ref requiredLength))
Marshal.ThrowExceptionForHR(Marshal.GetHRForLastWin32Error());
}
else
{
throw new Win32Exception();
}
}
List<string> displayNames = new List<string>();
StringBuilder displayName = new StringBuilder();
for (int i = 0; i < requiredLength; i++)
{
if (buffer[i] == '\0')
{
if (displayName.Length > 0)
displayNames.Add(displayName.ToString());
displayName.Length = 0;
}
else
{
displayName.Append(buffer[i]);
}
}
return displayNames.ToArray();
}
19
Source : Volumes.cs
with MIT License
from alexis-
with MIT License
from alexis-
public static bool IsVolume(IUIHost host, string volumePath)
{
if (volumePath == null)
throw new ArgumentNullException("volumePath");
if (volumePath.Length == 0)
return false;
host.WriteVerbose("- Checking if \"{0}\" is a real volume path...", volumePath);
if (!volumePath.EndsWith("\\"))
volumePath = volumePath + "\\";
StringBuilder volumeNameBuilder = new StringBuilder(NativeMethods.MAX_PATH);
if (ClusterIsPathOnSharedVolume(host, volumePath))
{
if (!NativeMethods.ClusterGetVolumeNameForVolumeMountPointW(volumePath, volumeNameBuilder, (uint)volumeNameBuilder.Capacity))
{
host.WriteVerbose("- ClusterGetVolumeNameForVolumeMountPointW(\"{0}\") failed with error code {1}.", volumePath, Marshal.GetLastWin32Error());
return false;
}
return true;
}
else
{
if (!NativeMethods.GetVolumeNameForVolumeMountPointW(volumePath, volumeNameBuilder, (uint)volumeNameBuilder.Capacity))
{
host.WriteVerbose("- GetVolumeNameForVolumeMountPoint(\"{0}\") failed with error code {1}.", volumePath, Marshal.GetLastWin32Error());
return false;
}
return true;
}
}
19
Source : Volumes.cs
with MIT License
from alexis-
with MIT License
from alexis-
public static string GetUniqueVolumeNameForPath(IUIHost host, string path, bool isBackup)
{
if (path == null)
throw new ArgumentNullException("path");
if (path.Length == 0)
throw new ArgumentException("Mount point must be non-empty");
host.WriteVerbose("- Get volume path name for \"{0}\"...", path);
if (!path.EndsWith("\\"))
path = path + "\\";
if (isBackup && ClusterIsPathOnSharedVolume(host, path))
{
string volumeRootPath, volumeUniqueName;
ClusterPrepareSharedVolumeForBackup(path, out volumeRootPath, out volumeUniqueName);
host.WriteVerbose("- Path name: {0}", volumeRootPath);
host.WriteVerbose("- Unique volume name: {0}", volumeUniqueName);
return volumeUniqueName;
}
else
{
// Get the root path of the volume
StringBuilder volumeRootPath = new StringBuilder(NativeMethods.MAX_PATH);
if (!NativeMethods.GetVolumePathNameW(path, volumeRootPath, (uint)volumeRootPath.Capacity))
{
host.WriteVerbose("- GetVolumePathName(\"{0}\") failed with error code {1}", path, Marshal.GetLastWin32Error());
throw new Win32Exception();
}
// Get the volume name alias (might be different from the unique volume name in rare cases)
StringBuilder volumeName = new StringBuilder(NativeMethods.MAX_PATH);
if (!NativeMethods.GetVolumeNameForVolumeMountPointW(volumeRootPath.ToString(), volumeName, (uint)volumeName.Capacity))
{
host.WriteVerbose("- GetVolumeNameForVolumeMountPoint(\"{0}\") failed with error code {1}", volumeRootPath.ToString(), Marshal.GetLastWin32Error());
throw new Win32Exception();
}
// Gte the unique volume name
StringBuilder uniqueVolumeName = new StringBuilder(NativeMethods.MAX_PATH);
if (!NativeMethods.GetVolumeNameForVolumeMountPointW(volumeName.ToString(), uniqueVolumeName, (uint)uniqueVolumeName.Capacity))
{
host.WriteVerbose("- GetVolumeNameForVolumeMountPoint(\"{0}\") failed with error code {1}", volumeName.ToString(), Marshal.GetLastWin32Error());
throw new Win32Exception();
}
return uniqueVolumeName.ToString();
}
}
See More Examples