public static StringBuilder AppendEscapedJson(StringBuilder builder, string value) { if (value == null) return builder; builder.EnsureCapacity(builder.Length + value.Length + 5); for (var i = 0; i < value.Length; i++) { switch (value[i]) { case '\t': builder.Append(@"\t"); break; case '\n': builder.Append(@"\n"); break; case '\r': builder.Append(@"\r"); break; case '"': builder.Append(@"\"""); break; case '\\': builder.Append(@"\\"); break; default: builder.Append(value[i]); break; } } return builder; }
public static char[] GetDriveLetters(string driveName) { List<char> results = new List<char>(); StringBuilder sb = new StringBuilder(128); for (char ch = 'A'; ch < 'Z'; ch++) { uint result; do { result = QueryDosDevice(ch + ":", sb, (uint)sb.Capacity); if (result == 122) sb.EnsureCapacity(sb.Capacity * 2); } while (result == 122); // Contains target? string[] drives = sb.ToString().Split('\0'); if (drives.Any(s => s.Equals(driveName, StringComparison.InvariantCultureIgnoreCase))) results.Add(ch); } return results.ToArray(); }
public static string GetCompactPath(this FileSystemInfo info, int newWidth, Font drawFont) { using (Control ctrl = new Control()) { Graphics g = ctrl.CreateGraphics(); string longPath = info.FullName; int width = g.MeasureString(longPath, drawFont).ToSize().Width; if (width <= newWidth) return longPath; int aveCharWidth = width / longPath.Length; int charCount = newWidth / aveCharWidth; StringBuilder builder = new StringBuilder(); builder.Append(longPath); builder.EnsureCapacity(charCount); while (g.MeasureString(builder.ToString(), drawFont).Width > newWidth) { if (!NativeMethods.PathCompactPathEx(builder, longPath, (uint)charCount--, 0)) { return string.Empty; } } return builder.ToString(); } }
/// <summary> /// Resolves A Specified LUID Value Into The Apropriate Windows Privilege /// </summary> public static String GetPrivilegeName(Win32API.LUID luid) { try { StringBuilder _PrivilegeName = new StringBuilder(); //hold the length of the LuID Struct Int32 _NameLength = 0; //first method call is to get the _NameLength so we can allocate a buffer Win32API.LookupPrivilegeName(String.Empty, ref luid, _PrivilegeName, ref _NameLength); //make sure there is sufficient space in memory _PrivilegeName.EnsureCapacity(_NameLength); //look up the privilage name if (Win32API.LookupPrivilegeName(String.Empty, ref luid, _PrivilegeName, ref _NameLength)) { return _PrivilegeName.ToString(); }//if (Win32API.LookupPrivilegeName(String.Empty, ref luid, _PrivilegeName, ref _NameLength)) } catch (Exception) { Console.WriteLine("## ERROR ## - Problem Getting Privilege Name!\nWin32 Error: '{0}', LUID '{1}'", Marshal.GetLastWin32Error(), luid); }//end of try-catch //default catch all return String.Empty; }
private string GetClassName(IntPtr hwnd) { StringBuilder sb = new StringBuilder(); sb.EnsureCapacity(1024); Interop.GetClassName(hwnd, sb, sb.Capacity); return sb.ToString(); }
public static unsafe string GetUsername(this SecurityIdentifier securityIdentifier, string systemName = null) { var name = new StringBuilder(); uint nameSize = (uint)name.Capacity; var domain = new StringBuilder(); uint domainSize = (uint)domain.Capacity; SidNameUse use; fixed (void* ptr = GetBinaryForm(securityIdentifier)) { var sid = new IntPtr(ptr); if (NativeMethods.LookupAccountSid(systemName, sid, name, ref nameSize, domain, ref domainSize, out use)) { return name.ToString(); } var error = (SystemErrorCode)Marshal.GetLastWin32Error(); if (error != SystemErrorCode.ErrorInsufficientBuffer) { throw ErrorHelper.GetWin32Exception(error); } name.EnsureCapacity((int)nameSize); domain.EnsureCapacity((int)domainSize); if (!NativeMethods.LookupAccountSid(systemName, sid, name, ref nameSize, domain, ref domainSize, out use)) { throw ErrorHelper.GetWin32Exception(); } } return name.ToString(); }
/// <summary> /// Returns the version string and language string in the format that the installer /// expects to find them in the database. If you just want version information, set /// lpLangBuf and pcchLangBuf to zero. If you just want language information, set /// lpVersionBuf and pcchVersionBuf to zero. /// </summary> /// <param name="filePath">Specifies the path to the file.</param> /// <param name="version">Returns the file version. Set to 0 for language information only.</param> /// <param name="language">Returns the file language. Set to 0 for version information only.</param> public static void FileVersion(string filePath, out string version, out string language) { int versionLength = 20; int languageLength = 20; StringBuilder versionBuffer = new StringBuilder(versionLength); StringBuilder languageBuffer = new StringBuilder(languageLength); uint er = MsiInterop.MsiGetFileVersion(filePath, versionBuffer, ref versionLength, languageBuffer, ref languageLength); if (234 == er) { versionBuffer.EnsureCapacity(++versionLength); languageBuffer.EnsureCapacity(++languageLength); er = MsiInterop.MsiGetFileVersion(filePath, versionBuffer, ref versionLength, languageBuffer, ref languageLength); } else if (1006 == er) { er = 0; // file has no version or language, so no error } if (0 != er) { throw new System.Runtime.InteropServices.ExternalException(String.Format("Unknown error while getting version of file: {0}, system error: {1}", filePath, er)); } version = versionBuffer.ToString(); language = languageBuffer.ToString(); }
public void Check() { try { var builder = new StringBuilder(); var specialPrivileges = new List <string>() { "SeSecurityPrivilege", "SeTakeOwnershipPrivilege", "SeLoadDriverPrivilege", "SeBackupPrivilege", "SeRestorePrivilege", "SeDebugPrivilege", "SeSystemEnvironmentPrivilege", "SeImpersonatePrivilege", "SeTcbPrivilege" }; int TokenInfLength = 0; IntPtr ThisHandle = WindowsIdentity.GetCurrent().Token; advapi32.GetTokenInformation(ThisHandle, advapi32.TOKEN_INFORMATION_CLASS.TokenPrivileges, IntPtr.Zero, TokenInfLength, out TokenInfLength); IntPtr TokenInformation = Marshal.AllocHGlobal(TokenInfLength); if (advapi32.GetTokenInformation(WindowsIdentity.GetCurrent().Token, advapi32.TOKEN_INFORMATION_CLASS.TokenPrivileges, TokenInformation, TokenInfLength, out TokenInfLength)) { var ThisPrivilegeSet = (advapi32.TOKEN_PRIVILEGES)Marshal.PtrToStructure(TokenInformation, typeof(advapi32.TOKEN_PRIVILEGES)); for (int i = 0; i < ThisPrivilegeSet.PrivilegeCount; i++) { advapi32.LUID_AND_ATTRIBUTES laa = ThisPrivilegeSet.Privileges[i]; System.Text.StringBuilder StrBuilder = new System.Text.StringBuilder(); int LuidNameLen = 0; IntPtr LuidPointer = Marshal.AllocHGlobal(Marshal.SizeOf(laa.Luid)); Marshal.StructureToPtr(laa.Luid, LuidPointer, true); advapi32.LookupPrivilegeName(null, LuidPointer, null, ref LuidNameLen); StrBuilder.EnsureCapacity(LuidNameLen + 1); if (advapi32.LookupPrivilegeName(null, LuidPointer, StrBuilder, ref LuidNameLen)) { var privilage = StrBuilder.ToString(); if (specialPrivileges.Contains(privilage)) { builder.AppendLine("\t" + privilage + " [*]"); } else { builder.AppendLine("\t" + privilage); } } Marshal.FreeHGlobal(LuidPointer); } } Message = builder.ToString(); } catch { Message = "\tCheck failed [*]"; } }
/* A good summary of the code used to process arguments in most windows programs can be found at : * http://www.daviddeley.com/autohotkey/parameters/parameters.htm#WINARGV */ static void AppendEscaped(StringBuilder builder, string arg) { builder.EnsureCapacity(builder.Length + arg.Length); var needQuote = false; var containsQuoteOrBackslash = false; foreach(var c in arg) { needQuote |= (c == ' '); needQuote |= (c == '\t'); containsQuoteOrBackslash |= (c == '"'); containsQuoteOrBackslash |= (c == '\\'); } if (needQuote) { builder.Append('"'); } else if (!containsQuoteOrBackslash) { // No special characters are present, early exit builder.Append(arg); return; } var index = 0; var backslashes = 0; while (index < arg.Length) { var c = arg[index]; if (c == '\\') { backslashes++; } else if (c == '"') { AddBackslashes(builder, backslashes, true); backslashes = 0; builder.Append('\\'); builder.Append(c); } else { AddBackslashes(builder, backslashes, false); backslashes = 0; builder.Append(c); } index += 1; } AddBackslashes(builder, backslashes, needQuote); if (needQuote) { builder.Append('"'); } }
public MainWindow() { InitializeComponent(); Output = new StringBuilder(); Output.EnsureCapacity(MAX_CAPACITY); LastKnownFileName = ""; Calculator = gcalc.gcalc_create(); Title = string.Format("gkalk {0}", AppVersion.Get()); }
public void StringStringBuilder(string inArg, StringBuilder outArg) { // ɾ��ԭ������ outArg.Remove(0, outArg.Length); // ȷ��StringBuilder���������㹻������ outArg.EnsureCapacity(inArg.Length + "_�����(StringBuilder)".Length); outArg.Append(inArg); outArg.Append("_�����(StringBuilder)"); }
public override void Decode(Asn1BerDecodeBuffer buffer, bool explicitTagging, int implicitLength) { var elemLength = explicitTagging ? MatchTag(buffer, Tag) : implicitLength; var len = elemLength; var sb = new StringBuilder(); var lastTag = buffer.LastTag; if ((lastTag == null) || !lastTag.Constructed) { sb.EnsureCapacity(elemLength / 2); ReadSegment(buffer, sb, len); } else { var capacity = 0; var context = new Asn1BerDecodeContext(buffer, elemLength); while (!context.Expired()) { var num3 = MatchTag(buffer, Asn1OctetString.Tag); if (num3 <= 0) { throw ExceptionUtility.CryptographicException(Resources.Asn1InvalidFormatOfConstructedValue, buffer.ByteCount); } capacity += num3; sb.EnsureCapacity(capacity); ReadSegment(buffer, sb, num3); } if (elemLength == Asn1Status.IndefiniteLength) { MatchTag(buffer, Asn1Tag.Eoc); } } Value = sb.ToString(); buffer.TypeCode = BmpStringTypeCode; }
/// <summary> /// Encodes the given byte range from the given source buffer, sets the codedStr to the resulting encoded hex string and returns true if the operation was successful. /// </summary> /// <param name="sourceBuffer">specifies the source buffer from which to encode bytes</param> /// <param name="startOffset">specifies the index of the first byte in the source buffer</param> /// <param name="length">specifies the number of bytes to encode from the source buffer</param> /// <param name="codedStr">the output string parameter that will be set to the encoded string</param> /// <returns>true if the operation was successful, false otherwise. The contents of the resulting encoded string are not defined if the return value is false.</returns> public override bool Encode(byte[] sourceBuffer, int startOffset, int length, out string codedStr) { codedStr = string.Empty; System.Text.StringBuilder sb = new System.Text.StringBuilder(); if (sourceBuffer == null) { sourceBuffer = emptyArray; } int sbLength = sourceBuffer.Length; if (startOffset >= sbLength) { return(false); } int endOffset = startOffset + length; bool success = true; if (endOffset > sbLength) { endOffset = sbLength; success = false; } sb.EnsureCapacity((endOffset - startOffset) * 3); int lastIdx = endOffset - 1; for (int idx = startOffset; idx <= lastIdx; idx++) { if (UseUpperCase) { sb.CheckedAppendFormat("{0:X2}", unchecked ((int)sourceBuffer[idx])); } else { sb.CheckedAppendFormat("{0:x2}", unchecked ((int)sourceBuffer[idx])); } bool isLastByte = (idx == lastIdx); bool appendSeperator = !isLastByte && (((idx % 2) == 0) ? UseWordSeperator : UseByteSeperator); if (appendSeperator) { sb.Append(" "); } } codedStr = sb.ToString(); return(success); }
public static void Main() { File.WriteAllText("steam_appid.txt", "630"); Steamworks.Load(true); ISteamClient006 steamclient = Steamworks.CreateInterface<ISteamClient006>(); int pipe = steamclient.CreateSteamPipe(); int user = steamclient.ConnectToGlobalUser(pipe); // steamclient.CreateLocalUser(ref pipe); // steamclient.ConnectToGlobalUser(pipe); ISteamUser004 steamuser = steamclient.GetISteamUser<ISteamUser004>(user, pipe); ISteam003 steam003 = Steamworks.CreateSteamInterface<ISteam003>(); StringBuilder version = new StringBuilder(); version.EnsureCapacity(256); steam003.GetVersion(version); TSteamError error = new TSteamError(); uint sz = 0; StringBuilder email = new StringBuilder(); email.EnsureCapacity(256); steam003.GetCurrentEmailAddress(email, ref sz, ref error); CSteamID steamid = steamuser.GetSteamID(); ISteamFriends003 friends = steamclient.GetISteamFriends<ISteamFriends003>(user, pipe); ISteamFriends002 friends2 = steamclient.GetISteamFriends<ISteamFriends002>(user, pipe); int num = friends.GetFriendCount(EFriendFlags.k_EFriendFlagAll); for (int i = 0; i < num; i++) { CSteamID id = friends.GetFriendByIndex(i, EFriendFlags.k_EFriendFlagAll); string name = friends.GetFriendPersonaName(id); if (name == "Stan") { byte[] buff = Encoding.ASCII.GetBytes("Oidy."); friends2.SendMsgToFriend(id, EChatEntryType.k_EChatEntryTypeChatMsg, buff); } Debug.WriteLine(name); } }
static public int EnsureCapacity(IntPtr l) { try { System.Text.StringBuilder self = (System.Text.StringBuilder)checkSelf(l); System.Int32 a1; checkType(l, 2, out a1); var ret = self.EnsureCapacity(a1); pushValue(l, true); pushValue(l, ret); return(2); } catch (Exception e) { return(error(l, e)); } }
static void Main(String[] args) { int numCases = int.Parse(Console.ReadLine()); for (int i = 0; i < numCases; i++) { string first = Console.ReadLine(); string second = Console.ReadLine(); int current1 = 0; int current2 = 0; StringBuilder output = new StringBuilder(); output.EnsureCapacity(first.Length + second.Length); while (current1 < first.Length && current2 < second.Length) { if (first[current1] < second[current2]) { output.Append(first[current1]); current1++; } else if (first[current1] > second[current2]) { output.Append(second[current2]); current2++; } else { if (first.Substring(current1).CompareTo(second.Substring(current2)) < 0 ) { output.Append(first[current1]); current1++; } else { output.Append(second[current2]); current2++; } } } if (current1 < first.Length) { output.Append(first.Substring(current1)); } else { output.Append(second.Substring(current2)); } Console.WriteLine(output); } }
/// <summary> /// Quotes the string. /// </summary> /// <param name="s">The s.</param> /// <param name="quoteChar">The quote char.</param> /// <param name="sb">The sb.</param> internal static void QuoteString(string s, char quoteChar, StringBuilder sb) { if (s == null || (s.Length == 1 && s[0] == '\0')) { sb.Append(new String(quoteChar, 2)); return; } char c; int len = s.Length; sb.EnsureCapacity(sb.Length + s.Length + 2); sb.Append(quoteChar); for (int i = 0; i < len; i++) { c = s[i]; switch (c) { case '\\': sb.Append("\\\\"); break; case '\b': sb.Append("\\b"); break; case '\t': sb.Append("\\t"); break; case '\r': sb.Append("\\r"); break; case '\n': sb.Append("\\n"); break; case '\f': sb.Append("\\f"); break; default: if (c < ' ') { sb.Append("\\u"); sb.Append(((int)c).ToString("x4", CultureInfo.InvariantCulture)); } else if (c == quoteChar) { sb.Append("\\"); sb.Append(c); } else { sb.Append(c); } break; } } sb.Append(quoteChar); }
/// <summary> /// Retrieves the multilingual string associated with the specified name. Returns null if the name/value pair does not exist in the registry. /// The key must have been opened using /// </summary> /// <param name = "key">The registry key to load the string from.</param> /// <param name = "name">The name of the string to load.</param> /// <returns>The language-specific string, or null if the name/value pair does not exist in the registry.</returns> public static string LoadMuiStringValue( this RegistryKey key, string name ) { const int initialBufferSize = 1024; var output = new StringBuilder( initialBufferSize ); int requiredSize; IntPtr keyHandle = key.Handle.DangerousGetHandle(); ErrorCode result = (ErrorCode)AdvApi32.RegLoadMUIString( keyHandle, name, output, output.Capacity, out requiredSize, AdvApi32.RegistryLoadMuiStringOptions.None, null ); if ( result == ErrorCode.MoreData ) { output.EnsureCapacity( requiredSize ); result = (ErrorCode)AdvApi32.RegLoadMUIString( keyHandle, name, output, output.Capacity, out requiredSize, AdvApi32.RegistryLoadMuiStringOptions.None, null ); } return result == ErrorCode.Success ? output.ToString() : null; }
public static void GetSpecialTokenGroupPrivs() { // Returns all "special" privileges that the current process/user possesses // adapted from https://stackoverflow.com/questions/4349743/setting-size-of-token-privileges-luid-and-attributes-array-returned-by-gettokeni Console.WriteLine("\r\n\r\n=== *Special* User Privileges ===\r\n"); string[] SpecialPrivileges = { "SeSecurityPrivilege", "SeTakeOwnershipPrivilege", "SeLoadDriverPrivilege", "SeBackupPrivilege", "SeRestorePrivilege", "SeDebugPrivilege", "SeSystemEnvironmentPrivilege", "SeImpersonatePrivilege", "SeTcbPrivilege" }; int TokenInfLength = 0; IntPtr ThisHandle = WindowsIdentity.GetCurrent().Token; GetTokenInformation(ThisHandle, TOKEN_INFORMATION_CLASS.TokenPrivileges, IntPtr.Zero, TokenInfLength, out TokenInfLength); IntPtr TokenInformation = Marshal.AllocHGlobal(TokenInfLength); if (GetTokenInformation(WindowsIdentity.GetCurrent().Token, TOKEN_INFORMATION_CLASS.TokenPrivileges, TokenInformation, TokenInfLength, out TokenInfLength)) { TOKEN_PRIVILEGES ThisPrivilegeSet = (TOKEN_PRIVILEGES)Marshal.PtrToStructure(TokenInformation, typeof(TOKEN_PRIVILEGES)); for (int index = 0; index < ThisPrivilegeSet.PrivilegeCount; index++) { LUID_AND_ATTRIBUTES laa = ThisPrivilegeSet.Privileges[index]; System.Text.StringBuilder StrBuilder = new System.Text.StringBuilder(); int LuidNameLen = 0; IntPtr LuidPointer = Marshal.AllocHGlobal(Marshal.SizeOf(laa.Luid)); Marshal.StructureToPtr(laa.Luid, LuidPointer, true); LookupPrivilegeName(null, LuidPointer, null, ref LuidNameLen); StrBuilder.EnsureCapacity(LuidNameLen + 1); if (LookupPrivilegeName(null, LuidPointer, StrBuilder, ref LuidNameLen)) { string privilege = StrBuilder.ToString(); foreach (string SpecialPrivilege in SpecialPrivileges) { if (privilege == SpecialPrivilege) { Console.WriteLine(String.Format(" {0,43}: {1}", privilege, (LuidAttributes)laa.Attributes)); } } } Marshal.FreeHGlobal(LuidPointer); } } }
public static void SetFileLength(SafeFileHandle fileHandle, long length) { var lo = (int)(length & 0xffffffff); var hi = (int)(length >> 32); int lastError; if (SetFilePointer(fileHandle, lo, out hi, Win32NativeFileMoveMethod.Begin) == -1) { lastError = Marshal.GetLastWin32Error(); if (lastError != 0) throw new Win32Exception(lastError); } if (SetEndOfFile(fileHandle) == false) { lastError = Marshal.GetLastWin32Error(); if (lastError == (int) Win32NativeFileErrors.ERROR_DISK_FULL) { var filePath = new StringBuilder(256); while (GetFinalPathNameByHandle(fileHandle, filePath, filePath.Capacity, 0) > filePath.Capacity && filePath.Capacity < 32767) // max unicode path length { filePath.EnsureCapacity(filePath.Capacity*2); } filePath = filePath.Replace(@"\\?\", string.Empty); // remove extended-length path prefix var fullFilePath = filePath.ToString(); var driveLetter = Path.GetPathRoot(fullFilePath); var driveInfo = new DriveInfo(driveLetter); throw new DiskFullException(driveInfo, fullFilePath, length); } var exception = new Win32Exception(lastError); if (lastError == (int) Win32NativeFileErrors.ERROR_NOT_READY || lastError == (int) Win32NativeFileErrors.ERROR_FILE_NOT_FOUND) throw new VoronUnrecoverableErrorException("Could not set the file size because it is inaccessible", exception); throw exception; } }
public static string _hexdump(WvBytes b) { if (b.bytes == null) return "(nil)"; var sb = new StringBuilder(); // This is overly complicated so that the body and header of // the same buffer can be printed separately yet still show the // proper alignment int rowoffset = b.start & (~0xf); // Note: it's important to set the right capacity when dealing // with large quantities of data. Assume about 80 chars per line. sb.EnsureCapacity((b.len / 16 + 2) * 80); for (int i = rowoffset; i < b.len; i += 16) { sb.Append('[').Append(i.ToString("x4")).Append("]"); for (int j = 0; j < 16; j++) { if ((j % 4)==0) sb.Append(' '); sb.Append(hexbyte(b, i+j)); } sb.Append(' '); for (int j = 0; j < 16; j++) { if ((j % 4)==0) sb.Append(' '); sb.Append(printable(b, i+j)); } sb.Append('\n'); } return sb.ToString(); }
public static string ByteArrayToHexDump( byte[] aBytes , int aBytesPerLine = 16 , string aSplitter = " | " ) { //<8 bytes address><aSplitter><aBytesPerLine's hex with (aBytesPerLine - 1)'s space><aSplitter><aBytesPerLine's ascii> int nOneLineSize = 8 + aSplitter.Length * 2 + aBytesPerLine * 4 - 1 + Environment.NewLine.Length; StringBuilder strBuilder = new StringBuilder(); strBuilder.EnsureCapacity( (int)Math.Ceiling((double)aBytes.Length/(double)aBytesPerLine) * nOneLineSize ); for ( int i = 0 ; i < aBytes.Length ; i += aBytesPerLine ) { strBuilder.AppendFormat( "{0:X8}{1}" , i , aSplitter ); for ( int j = 0 ; j < aBytesPerLine ; j++ ) { int nCurr = i + j; if ( nCurr >= aBytes.Length ) { strBuilder.Append( ' ' , (aBytesPerLine - j) * 3 - 1 ); break; } var val = m_lookup32[aBytes[nCurr]]; strBuilder.Append( (char)val ); strBuilder.Append( (char)(val >> 16) ); if ( j + 1 < aBytesPerLine ) { strBuilder.Append( ' ' ); } } strBuilder.Append( aSplitter ); for ( int j = 0 ; j < aBytesPerLine ; j++ ) { int nCurr = i + j; if ( nCurr >= aBytes.Length ) { strBuilder.Append( ' ' , aBytesPerLine - j ); break; } strBuilder.Append( char.IsControl((char)aBytes[nCurr]) ? '.' : (char)aBytes[nCurr] ); } strBuilder.AppendLine(); } return strBuilder.ToString(); }
public static string Serialize(Object target, bool prettyPrint) { StringBuilder sbSerialized = new StringBuilder(); JavaScriptSerializer js = new JavaScriptSerializer(); js.Serialize(target, sbSerialized); if (prettyPrint) { StringBuilder prettyPrintedResult = new StringBuilder(); prettyPrintedResult.EnsureCapacity(sbSerialized.Length); JsonPrettyPrinter pp = new JsonPrettyPrinter(); pp.PrettyPrint(sbSerialized, prettyPrintedResult); return prettyPrintedResult.ToString(); } else return sbSerialized.ToString(); }
public static List <string[]> getTokenPrivileges(IntPtr tHandle) { List <string[]> privileges = new List <string[]>(); uint TokenInfLength = 0; bool Result; //Get TokenInformation length in TokenInfLength Result = GetTokenInformation(tHandle, TOKEN_INFORMATION_CLASS.TokenPrivileges, IntPtr.Zero, TokenInfLength, out TokenInfLength); IntPtr TokenInformation = Marshal.AllocHGlobal((int)TokenInfLength); Result = GetTokenInformation(tHandle, TOKEN_INFORMATION_CLASS.TokenPrivileges, TokenInformation, TokenInfLength, out TokenInfLength); if (Result == false) { Console.Out.Write("\r\nGetTokenInformation failed with error code " + Marshal.GetLastWin32Error()); System.Environment.Exit(0); } TOKEN_PRIVILEGES TokenPrivileges = ( TOKEN_PRIVILEGES )Marshal.PtrToStructure(TokenInformation, typeof(TOKEN_PRIVILEGES)); for (int i = 0; i < TokenPrivileges.PrivilegeCount; i++) { System.Text.StringBuilder sb = new System.Text.StringBuilder(); int luidNameLen = 0; LUID luid = new LUID(); string[] privilegeStatus = new string[2]; luid = TokenPrivileges.Privileges[i].Luid; IntPtr ptrLuid = Marshal.AllocHGlobal(Marshal.SizeOf(luid)); Marshal.StructureToPtr(luid, ptrLuid, true); LookupPrivilegeName(null, ptrLuid, null, ref luidNameLen); // call once to get the name len sb.EnsureCapacity(luidNameLen + 1); Result = LookupPrivilegeName(null, ptrLuid, sb, ref luidNameLen); // call again to get the name if (Result == false) { Console.Out.Write("\r\nLookupPrivilegeName failed with error code " + Marshal.GetLastWin32Error()); System.Environment.Exit(0); } privilegeStatus[0] = sb.ToString(); privilegeStatus[1] = convertAttributeToString(TokenPrivileges.Privileges[i].Attributes); privileges.Add(privilegeStatus); } return(privileges); }
/// <summary>Gets the relative path from <paramref name="basePath"/> to <paramref name="pathName"/>.</summary> /// <param name="basePath">The path to use as the root path.</param> /// <param name="pathName">The path to obtain the relative path of.</param> /// <returns>The relative path from <paramref name="basePath"/> to <paramref name="pathName"/>.</returns> /// <exception cref="ArgumentNullException"><paramref name="basePath"/> is <see langword="null"/>.</exception> /// <exception cref="ArgumentException"><paramref name="basePath"/> is empty or invalid.</exception> /// <example> /// <code lang="C#"> /// struct PathData /// { /// public string RootPath; /// public string PathName; /// /// public PathData ( string root, string path ) /// { /// RootPath = path; /// PathName = path; /// } /// } /// /// class App /// { /// static void Main ( ) /// { /// PathData[] arr = new PathData[] { /// new PathData(@"C:\Windows", @"C:\Windows\System32"), /// new PathData(@"C:\Temp", @"C:\Windows"), /// new PathData(@"C:\Windows", @"D:\"), /// new PathData(@"C:\Windows\System32, @"C:\Windows\System32") /// }; /// /// foreach(PathData data in arr) /// Console.WriteLine("Relative path from '{0}' to '{1}' is: {2}", data.RootPath, data.PathName, /// PathExtensions.GetRelativePath(data.RootPath, data.PathName)); /// } /// } /// /// /* Output is /// /// Relative path from 'C:\Windows' to 'C:\Windows\System32' is: .\System32 /// Relative path from 'C:\Temp' to 'C:\Windows' is: ..\Windows /// Relative path from 'C:\Windows' to 'D:\' is: D:\ /// Relative path from 'C:\Windows\System32' to 'C:\Windows\System32' is: . /// */ /// </code> /// </example> public static string GetRelativePath(string basePath, string pathName) { Verify.Argument("basePath", basePath).IsNotNullOrEmpty(); pathName = pathName ?? ""; //Determine if we are dealing with files or directories (use heuristics) string file = Path.GetFileName(basePath); var fromAttribute = file.Contains(".") ? FileAttributes.Normal : FileAttributes.Directory; file = Path.GetFileName(pathName); var toAttribute = file.Contains(".") ? FileAttributes.Normal : FileAttributes.Directory; System.Text.StringBuilder bldr = new System.Text.StringBuilder(); bldr.EnsureCapacity(260); if (!SafeNativeMethods.PathRelativePathToW(bldr, basePath, fromAttribute, pathName, toAttribute)) { return(pathName); } return(bldr.ToString()); }
private static System.Text.StringBuilder InitStringBuffer(int capacity) { if (mStringBuff == null) { mStringBuff = new System.Text.StringBuilder(capacity); } else { if (mStringBuff.Length > 0) { mStringBuff.Remove(0, mStringBuff.Length); } if (mStringBuff.Capacity < capacity) { mStringBuff.EnsureCapacity(capacity); } } return(mStringBuff); }
public virtual void printX() { const string sep = ", "; if (m_DebugStringBuilder == null) { m_DebugStringBuilder = new System.Text.StringBuilder(); } m_DebugStringBuilder.Remove(0, m_DebugStringBuilder.Length); m_DebugStringBuilder.EnsureCapacity(GetM() * GetN() * 64 * 2); for (int i = 0; i < GetM(); i++) { for (int j = 0; j < GetN(); j++) { m_DebugStringBuilder.Append(GetValue(i, j)); m_DebugStringBuilder.Append(sep); } m_DebugStringBuilder.Append("\n"); } Debug.Log(m_DebugStringBuilder.ToString()); }
public static void SetFileLength(SafeFileHandle fileHandle, long length) { var lo = (int)(length & 0xffffffff); var hi = (int)(length >> 32); int lastError; if (SetFilePointer(fileHandle, lo, out hi, Win32NativeFileMoveMethod.Begin) == -1) { lastError = Marshal.GetLastWin32Error(); if (lastError != 0) throw new Win32Exception(lastError); } if (SetEndOfFile(fileHandle) == false) { lastError = Marshal.GetLastWin32Error(); if (lastError == (int) Win32NativeFileErrors.DiskFull) { var filePath = new StringBuilder(256); while (GetFinalPathNameByHandle(fileHandle, filePath, filePath.Capacity, 0) > filePath.Capacity && filePath.Capacity < 32767) // max unicode path length { filePath.EnsureCapacity(filePath.Capacity*2); } filePath = filePath.Replace(@"\\?\", string.Empty); // remove extended-length path prefix var fullFilePath = filePath.ToString(); var driveLetter = Path.GetPathRoot(fullFilePath); var driveInfo = new DriveInfo(driveLetter); throw new DiskFullException(driveInfo, fullFilePath, length); } throw new Win32Exception(lastError); } }
/// <summary> /// Searches for the given account name and returns the SID associated with that account. Local machine accounts are searched first, then the primary domain, then trusted domains. Using fully-qualified account names is highly recommended, but not required. /// </summary> /// <param name="AccountName">A string value containing the account name to search for.</param> /// <returns>A string value containing the SID for the specified account, or an error msg if the SID could not be retrieved.</returns> public static string GetUserSid(string AccountName) { byte[] Sid = null; uint cbSid = 0; StringBuilder refDomainName = new StringBuilder(); uint cchRefDomainName = (uint)refDomainName.Capacity; SID_NAME_USE sidUse; int err = ERROR_SUCCESS; if (!LookupAccountName(null, AccountName, Sid, ref cbSid, refDomainName, ref cchRefDomainName, out sidUse)) { err = Marshal.GetLastWin32Error(); if (err == ERROR_INSUFFICIENT_BUFFER) { Sid = new byte[cbSid]; refDomainName.EnsureCapacity((int)cchRefDomainName); err = ERROR_SUCCESS; if (!LookupAccountName(null, AccountName, Sid, ref cbSid, refDomainName, ref cchRefDomainName, out sidUse)) err = Marshal.GetLastWin32Error(); } } if (err == 0) { IntPtr ptrSid; if (!ConvertSidToStringSid(Sid, out ptrSid)) { err = Marshal.GetLastWin32Error(); return "Could not convert SID to string. Error : " + err.ToString(); } else { string sidString = Marshal.PtrToStringAuto(ptrSid); LocalFree(ptrSid); return sidString; } } else return "Error : " + err.ToString(); }
/// <summary> /// Gets the set of installed components for products in the indicated context. /// </summary> /// <exception cref="InstallerException">The installer configuration data is corrupt</exception> /// <remarks><p> /// Win32 MSI API: /// <a href="http://msdn.microsoft.com/library/dd407947.aspx">MsiEnumComponentsEx</a> /// </p></remarks> public static IEnumerable<ComponentInstallation> Components(string szUserSid, UserContexts dwContext) { uint pcchSid = 32; StringBuilder szSid = new StringBuilder((int)pcchSid); StringBuilder buf = new StringBuilder(40); UserContexts installedContext; for (uint i = 0; true; i++) { uint ret = NativeMethods.MsiEnumComponentsEx(szUserSid, dwContext, i, buf, out installedContext, szSid, ref pcchSid); if (ret == (uint) NativeMethods.Error.MORE_DATA) { szSid.EnsureCapacity((int) ++pcchSid); ret = NativeMethods.MsiEnumComponentsEx(szUserSid, dwContext, i, buf, out installedContext, szSid, ref pcchSid); } if (ret == (uint) NativeMethods.Error.NO_MORE_ITEMS) break; if (ret != 0) { throw InstallerException.ExceptionFromReturnCode(ret); } yield return new ComponentInstallation(buf.ToString(), szSid.ToString(), installedContext); } }
public TokenPrivileges() { _name = "Abusable Token Privileges"; int TokenInfLength = 0; IntPtr ThisHandle = WindowsIdentity.GetCurrent().Token; GetTokenInformation(ThisHandle, TOKEN_INFORMATION_CLASS.TokenPrivileges, IntPtr.Zero, TokenInfLength, out TokenInfLength); IntPtr TokenInformation = Marshal.AllocHGlobal(TokenInfLength); if (GetTokenInformation(WindowsIdentity.GetCurrent().Token, TOKEN_INFORMATION_CLASS.TokenPrivileges, TokenInformation, TokenInfLength, out TokenInfLength)) { TOKEN_PRIVILEGES ThisPrivilegeSet = (TOKEN_PRIVILEGES)Marshal.PtrToStructure(TokenInformation, typeof(TOKEN_PRIVILEGES)); for (int index = 0; index < ThisPrivilegeSet.PrivilegeCount; index++) { LUID_AND_ATTRIBUTES laa = ThisPrivilegeSet.Privileges[index]; System.Text.StringBuilder StrBuilder = new System.Text.StringBuilder(); int LuidNameLen = 0; IntPtr LuidPointer = Marshal.AllocHGlobal(Marshal.SizeOf(laa.Luid)); Marshal.StructureToPtr(laa.Luid, LuidPointer, true); LookupPrivilegeName(null, LuidPointer, null, ref LuidNameLen); StrBuilder.EnsureCapacity(LuidNameLen + 1); if (LookupPrivilegeName(null, LuidPointer, StrBuilder, ref LuidNameLen)) { string privilege = StrBuilder.ToString(); foreach (string SpecialPrivilege in _specialPrivileges) { if (privilege == SpecialPrivilege) { _isVulnerable = true; _details.Add($"{privilege}: {(LuidAttributes)laa.Attributes}"); } } } Marshal.FreeHGlobal(LuidPointer); } } Marshal.FreeHGlobal(TokenInformation); }
/// <summary> /// Show the icon picker dialog. /// </summary> /// <param name="owner">Any object that implements IWin32Window that represents the top-level window that will own the modal dialog box.</param> /// <returns>DialogResult.OK if the user clicks OK in the dialog box; otherwise, DialogResult.Cancel.</returns> public DialogResult ShowDialog(IWin32Window owner) { if (this.IconFile == null || this.iconIndex == -1) { throw new ArgumentException("The icon file or index has not yet been specified."); } int tempIconIndex = this.iconIndex; StringBuilder iconFileBuffer = new StringBuilder(String.Empty); iconFileBuffer.EnsureCapacity(2048); if (NativeMethods.PickIconDlg(owner.Handle, iconFileBuffer, iconFileBuffer.Capacity, ref tempIconIndex) != 0) { string tempIconFile = Environment.ExpandEnvironmentVariables(iconFileBuffer.ToString()); IntPtr iconHandle = NativeMethods.ExtractIconW(Process.GetCurrentProcess().Handle, tempIconFile, tempIconIndex); if (iconHandle == IntPtr.Zero || iconHandle.ToInt32() == 1) { throw new ApplicationException(String.Format("Cannot load icon from '{0}' with index {1}.", tempIconFile, tempIconIndex)); } // hack to ensure the icon handle is properly freed Icon tempIcon = Icon.FromHandle(iconHandle); this.icon = (Icon)tempIcon.Clone(); tempIcon.Dispose(); NativeMethods.DestroyIcon(iconHandle); // save the new values this.iconFile = tempIconFile; this.iconIndex = tempIconIndex; return DialogResult.OK; } else { return DialogResult.Cancel; } }
public static string GetUserName(this Process targetProcess) { string userName = String.Empty; var name = new StringBuilder(); uint cchName = (uint)name.Capacity; StringBuilder referencedDomainName = new StringBuilder(); uint cchReferencedDomainName = (uint)referencedDomainName.Capacity; NativeMethods.SidNameUse sidUse; byte[] sid = GetProcessSidBytes(targetProcess); if (sid == null) { userName = "******"; } else { if (!NativeMethods.LookupAccountSid(null, sid, name, ref cchName, referencedDomainName, ref cchReferencedDomainName, out sidUse)) { int errorCode = Marshal.GetLastWin32Error(); if (errorCode == NativeMethods.Constants.ERROR_INSUFFICIENT_BUFFER) { name.EnsureCapacity((int)cchName); referencedDomainName.EnsureCapacity((int)cchReferencedDomainName); if (!NativeMethods.LookupAccountSid(null, sid, name, ref cchName, referencedDomainName, ref cchReferencedDomainName, out sidUse)) { throw new Win32Exception(); } } } userName = name.ToString(); } return userName; }
/// <summary> /// Encodes the given byte range from the given source buffer, sets the codedStr to the resulting encoded string and returns true if the operation was successful. /// </summary> /// <param name="sourceBuffer">specifies the source buffer from which to encode bytes</param> /// <param name="startOffset">specifies the index of the first byte in the source buffer</param> /// <param name="length">specifies the number of bytes to encode from the source buffer</param> /// <param name="codedStr">the output string parameter that will be set to the encoded string</param> /// <returns>true if the operation was successful, false otherwise. The contents of the resulting encoded string are not defined if the return value is false.</returns> public override bool Encode(byte[] sourceBuffer, int startOffset, int length, out string codedStr) { codedStr = string.Empty; System.Text.StringBuilder sb = new System.Text.StringBuilder(); if (sourceBuffer == null) { sourceBuffer = emptyArray; } int sbLength = sourceBuffer.Length; if (startOffset >= sbLength) { return(false); } int endOffset = startOffset + length; bool success = true; if (endOffset > sbLength) { endOffset = sbLength; success = false; } sb.EnsureCapacity(endOffset - startOffset); for (int idx = startOffset; idx < endOffset; idx++) { sb.Append((char)sourceBuffer [idx]); } codedStr = sb.ToString(); return(success); }
public static SecurityIdentifier Get(string accountName) { Log.Info("GetSid(" + accountName + ")"); byte[] Sid = null; uint cbSid = 0; StringBuilder referencedDomainName = new StringBuilder(); uint cchReferencedDomainName = (uint)referencedDomainName.Capacity; SID_NAME_USE sidUse; int err = NO_ERROR; if (!LookupAccountName(null, accountName, Sid, ref cbSid, referencedDomainName, ref cchReferencedDomainName, out sidUse)) { err = Marshal.GetLastWin32Error(); if (err == ERROR_INSUFFICIENT_BUFFER || err == ERROR_INVALID_FLAGS) { Sid = new byte[cbSid]; referencedDomainName.EnsureCapacity((int)cchReferencedDomainName); err = NO_ERROR; if (!LookupAccountName(null, accountName, Sid, ref cbSid, referencedDomainName, ref cchReferencedDomainName, out sidUse)) err = Marshal.GetLastWin32Error(); } } else { throw new InvalidOperationException("Unable to find SID for account " + accountName + " (errno=" + err + ")"); } if (err == NO_ERROR) { return new SecurityIdentifier(Sid, 0); } else { throw new InvalidOperationException("Unable to find SID for account " + accountName + " (errno=" + err + ")"); } }
// Returns a CLRRuntimeInfo for the runtime that the specified binary // will run against. public CLRRuntimeInfo GetRequestedRuntime(MetaHostPolicyFlags flags, String binaryPath, String configPath, ref StringBuilder version, ref StringBuilder imageVersion) { IStream configStream = null; if (configPath != null) { try { NativeMethods.SHCreateStreamOnFileEx(configPath, NativeMethods.Stgm.StgmRead, 0, // We're not creating a file, so no flags needed. false, // Do NOT create a new file. IntPtr.Zero, out configStream); } catch (EntryPointNotFoundException) { // Fall back on the older method. NativeMethods.SHCreateStreamOnFile(configPath, NativeMethods.Stgm.StgmRead, out configStream); } } // In case they're empty. version.EnsureCapacity(MaxVersionStringLength); uint versionCapacity = System.Convert.ToUInt32(version.Capacity); imageVersion.EnsureCapacity(MaxVersionStringLength); uint imageVersionCapacity = System.Convert.ToUInt32(imageVersion.Capacity); Guid ifaceId = typeof(ICLRRuntimeInfo).GUID; uint configFlags; object o = m_MHPolicy.GetRequestedRuntime(flags, binaryPath, configStream, version, ref versionCapacity, imageVersion, ref imageVersionCapacity, out configFlags, ref ifaceId); return new CLRRuntimeInfo(o); }
public static string GetModuleFileName(IntPtr hModule) { var buffer = new StringBuilder((int)Win32Value.MAX_PATH); while (true) { int size = _GetModuleFileName(hModule, buffer, buffer.Capacity); if (size == 0) { HRESULT.ThrowLastError(); } // GetModuleFileName returns nSize when it's truncated but does NOT set the last error. // MSDN documentation says this has changed in Windows 2000+. if (size == buffer.Capacity) { // Enlarge the buffer and try again. buffer.EnsureCapacity(buffer.Capacity * 2); continue; } return buffer.ToString(); } }
public void process() { //tokenize bool prevgood = false; bool currgood = false; string wordinprogress = ""; for (int i = 0; i < text.Length; i++) { char currch = text[i]; if (!isGood(currch)) { currgood = false; } else { currgood = true; } if (!prevgood && !currgood) { //do nothing } if (!prevgood && currgood) { wordinprogress = wordinprogress + text[i]; } if (prevgood && currgood) { wordinprogress = wordinprogress + text[i]; } if (prevgood && !currgood) { wordsList.Add(wordinprogress); wordinprogress = ""; } prevgood = currgood; } bool badchar = false; for (int i = 0; i < wordinprogress.Length; i++) { if (!isGood(wordinprogress[i])) { badchar = true; } } if (wordinprogress == "") { badchar = true; } if (!badchar) { wordsList.Add(wordinprogress); } if (OnProgressUpdate != null) { OnProgressUpdate(17); } wordsTotal = wordsList.Count; //lemmatize if (lemmatize) { for (int i = 0; i < wordsList.Count; i++) { System.Text.StringBuilder lemma = new System.Text.StringBuilder(); lemma.EnsureCapacity(32); LemmatizatorEngine.sol_GetLemmaW(hEngine, wordsList[i], lemma, 32); String slemma = lemma.ToString(); wordsList[i] = slemma; if (OnProgressUpdate != null) { OnProgressUpdate(17 + i * 83 / wordsList.Count); } } } //get to lowercase for (int i = 0; i < wordsList.Count; i++) { wordsList[i] = wordsList[i].ToLower(); } //count words for (int i = 0; i < wordsList.Count; i++) { int count = 1; int j = i + 1; while (j < wordsList.Count) { if (wordsList[i] == wordsList[j]) { count++; wordsList.RemoveAt(j); j--; } j++; } wordsCount.Add(count); } //delete numbers if (deletenumbers) { int i1 = 0; while (i1 < wordsList.Count) { int n; bool isNumeric = int.TryParse(wordsList[i1], out n); if (isNumeric) { wordsList.RemoveAt(i1); wordsCount.RemoveAt(i1); i1--; } i1++; } } //delete words from blacklist if (blacklistEnabled) { int i2 = 0; while (i2 < wordsList.Count) { for (int i3 = 0; i3 < blacklist.Count; i3++) { if (wordsList[i2] == blacklist[i3]) { wordsList.RemoveAt(i2); wordsCount.RemoveAt(i2); i2--; goto m1; } } m1 : i2++; } } //form the final list wordsUnique = wordsList.Count; }
/// <summary> /// If there is a message in GL info log then post it in the Axiom Log /// </summary> /// <param name="message">The info log message string is appended to this string.</param> /// <param name="handle">The GL object handle that is used to retrieve the info log</param> /// <returns></returns> public static string LogObjectInfo( string message, int handle ) { StringBuilder logMessage = new StringBuilder(); if ( handle > 0 ) { int infologLength = 0; Gl.glGetObjectParameterivARB( handle, Gl.GL_OBJECT_INFO_LOG_LENGTH_ARB, out infologLength ); if ( infologLength > 0 ) { int charsWritten = 0; logMessage.EnsureCapacity( infologLength + 1 ); Gl.glGetInfoLogARB( handle, infologLength, out charsWritten, logMessage ); if ( charsWritten > 0 ) { logMessage.Append( "\n" ); message += "\n" + logMessage.ToString(); } LogManager.Instance.Write( message ); } } return logMessage.ToString(); }
static IEnumerable<Tuple<string, ICLRRuntimeInfo>> GetCLRRuntimeInfos(Process process) { var clsid = new Guid("9280188D-0E8E-4867-B30C-7FA83884E8DE"); var riid = typeof(ICLRMetaHost).GUID; var mh = (ICLRMetaHost)NativeMethods.CLRCreateInstance(ref clsid, ref riid); IEnumUnknown iter; int hr = mh.EnumerateLoadedRuntimes(process.Handle, out iter); if (hr < 0) yield break; for (;;) { object obj; uint fetched; hr = iter.Next(1, out obj, out fetched); if (hr < 0 || fetched == 0) break; var rtInfo = (ICLRRuntimeInfo)obj; uint chBuffer = 0; var sb = new StringBuilder(300); hr = rtInfo.GetVersionString(sb, ref chBuffer); sb.EnsureCapacity((int)chBuffer); hr = rtInfo.GetVersionString(sb, ref chBuffer); yield return Tuple.Create(sb.ToString(), rtInfo); } }
public void Refresh() { StringBuilder sb = new StringBuilder(); // get caption sb.EnsureCapacity(10240); bool WindowTimedOut = false; UIntPtr lRes = new UIntPtr(1860); int lResult = SendMessageTimeout(Handle, WM_GETTEXT, 10240, sb, SMTO_ABORTIFHUNG, 1000, out lRes); if (lResult == 0) { Trace.TraceError("SendMessageTimeout() failed with {0}", Marshal.GetLastWin32Error()); WindowTimedOut = true; Objects[(int)WindowItemTypes.Title] = "?"; } else { //Trace.TraceInformation("lResult: {0}, lRes: {1}", lResult, lRes.ToUInt32()); Objects[(int)WindowItemTypes.Title] = sb.ToString(); } // get class name sb = new StringBuilder(); sb.EnsureCapacity(10240); GetClassName(Handle, sb, 10240); Objects[(int)WindowItemTypes.Class] = sb.ToString(); uint style = GetWindowLong(Handle, GWL_STYLE); Objects[(int)WindowItemTypes.Style] = DecodeWindowStyle(style); Objects[(int)WindowItemTypes.ExStyle] = GetWindowLong(Handle, GWL_EXSTYLE); Objects[(int)WindowItemTypes.ID] = GetWindowLong(Handle, GWL_ID); RECT r = new RECT(); GetWindowRect(Handle, ref r); Objects[(int)WindowItemTypes.Size] = string.Format("({0}, {1})", r.Width, r.Height); Objects[(int)WindowItemTypes.Position] = string.Format("({0}, {1})", r.Top, r.Left); UIntPtr ProcessID = new UIntPtr(0); uint ThreadID = GetWindowThreadProcessId(Handle, out ProcessID); Objects[(int)WindowItemTypes.TID] = ThreadID; Objects[(int)WindowItemTypes.PID] = ProcessID.ToUInt32(); ForegroundColor = Color.Black; if ((r.Width == r.Height) && (r.Width == 0)) { ForegroundColor = Color.Gray; } if ((style & WS_VISIBLE) == 0) { ForegroundColor = Color.Gray; } if (WindowTimedOut) { ForegroundColor = Color.Red; } }
//////////////////////////////////////////////////////////////////////////////// // Checks if a Privilege Exists and is Enabled //////////////////////////////////////////////////////////////////////////////// public static bool CheckTokenPrivilege(IntPtr hToken, string privilegeName, out bool exists, out bool enabled) { exists = false; enabled = false; //////////////////////////////////////////////////////////////////////////////// uint TokenInfLength = 0; advapi32.GetTokenInformation(hToken, Winnt._TOKEN_INFORMATION_CLASS.TokenPrivileges, IntPtr.Zero, 0, out TokenInfLength); if (TokenInfLength <= 0 || TokenInfLength > int.MaxValue) { Misc.GetWin32Error("GetTokenInformation - 1 " + TokenInfLength); return(false); } IntPtr lpTokenInformation = Marshal.AllocHGlobal((int)TokenInfLength); //////////////////////////////////////////////////////////////////////////////// if (!advapi32.GetTokenInformation(hToken, Winnt._TOKEN_INFORMATION_CLASS.TokenPrivileges, lpTokenInformation, TokenInfLength, out TokenInfLength)) { Misc.GetWin32Error("GetTokenInformation - 2 " + TokenInfLength); return(false); } Winnt._TOKEN_PRIVILEGES_ARRAY tokenPrivileges = (Winnt._TOKEN_PRIVILEGES_ARRAY)Marshal.PtrToStructure(lpTokenInformation, typeof(Winnt._TOKEN_PRIVILEGES_ARRAY)); Marshal.FreeHGlobal(lpTokenInformation); //////////////////////////////////////////////////////////////////////////////// for (int i = 0; i < tokenPrivileges.PrivilegeCount; i++) { System.Text.StringBuilder lpName = new System.Text.StringBuilder(); int cchName = 0; IntPtr lpLuid = Marshal.AllocHGlobal(Marshal.SizeOf(tokenPrivileges.Privileges[i])); Marshal.StructureToPtr(tokenPrivileges.Privileges[i].Luid, lpLuid, true); try { advapi32.LookupPrivilegeName(null, lpLuid, null, ref cchName); if (cchName <= 0 || cchName > int.MaxValue) { Misc.GetWin32Error("LookupPrivilegeName Pass 1"); continue; } lpName.EnsureCapacity(cchName + 1); if (!advapi32.LookupPrivilegeName(null, lpLuid, lpName, ref cchName)) { Misc.GetWin32Error("LookupPrivilegeName Pass 2"); continue; } if (lpName.ToString() != privilegeName) { continue; } exists = true; Winnt._PRIVILEGE_SET privilegeSet = new Winnt._PRIVILEGE_SET { PrivilegeCount = 1, Control = Winnt.PRIVILEGE_SET_ALL_NECESSARY, Privilege = new Winnt._LUID_AND_ATTRIBUTES[] { tokenPrivileges.Privileges[i] } }; int pfResult = 0; if (!advapi32.PrivilegeCheck(hToken, ref privilegeSet, out pfResult)) { Misc.GetWin32Error("PrivilegeCheck"); continue; } enabled = Convert.ToBoolean(pfResult); } catch (Exception ex) { Console.WriteLine(ex.Message); return(false); } finally { Marshal.FreeHGlobal(lpLuid); } } Console.WriteLine(); return(false); }