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


C# StringBuilder.EnsureCapacity方法代码示例

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


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

示例1: AppendEscapedJson

 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;
 }
开发者ID:rneuber1,项目名称:InnovatorAdmin,代码行数:30,代码来源:JsonFormatter.cs

示例2: GetUsername

        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();
        }
开发者ID:tdctaz,项目名称:NativeWindows,代码行数:33,代码来源:SecurityIdentifierExtensions.cs

示例3: GetDriveLetters

        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();
        }
开发者ID:LordMike,项目名称:RawDiskLib,代码行数:25,代码来源:DiskHelper.cs

示例4: GetCompactPath

 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();
        }
 }
开发者ID:RoDaniel,项目名称:featurehouse,代码行数:25,代码来源:IO.cs

示例5: GetClassName

 private string GetClassName(IntPtr hwnd)
 {
     StringBuilder sb = new StringBuilder();
     sb.EnsureCapacity(1024);
     Interop.GetClassName(hwnd, sb, sb.Capacity);
     return sb.ToString();
 }
开发者ID:AutoPDS,项目名称:Automatic-Primary-Display-Switcher,代码行数:7,代码来源:SystemProcessHookForm.cs

示例6: GetPrivilegeName

        /// <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;
        }
开发者ID:nccgroup,项目名称:WhoWasI,代码行数:32,代码来源:Privilages.cs

示例7: FileVersion

        /// <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();
        }
开发者ID:sillsdev,项目名称:FwSupportTools,代码行数:36,代码来源:MsiBase.cs

示例8: AppendEscaped

        /* 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('"');
            }
        }
开发者ID:haraldsteinlechner,项目名称:Paket,代码行数:60,代码来源:WindowsProcessArguments.cs

示例9: MainWindow

        public MainWindow()
        {
            InitializeComponent();

            Output = new StringBuilder();
            Output.EnsureCapacity(MAX_CAPACITY);
            LastKnownFileName = "";
            Calculator = gcalc.gcalc_create();
            Title = string.Format("gkalk {0}", AppVersion.Get());
        }
开发者ID:jwg4,项目名称:gtools,代码行数:10,代码来源:MainWindow.xaml.cs

示例10: StringStringBuilder

        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)");
        }
开发者ID:zhaohengyi,项目名称:dotNet_PInvoke,代码行数:11,代码来源:MarshalString.cs

示例11: Decode

        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;
        }
开发者ID:kapitanov,项目名称:GostCryptography,代码行数:41,代码来源:Asn1BmpString.cs

示例12: Main

        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);
            }
             
        }
开发者ID:AluminumKen,项目名称:hl2sb-src,代码行数:49,代码来源:Program.cs

示例13: QuoteString

		/// <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);
		}
开发者ID:kouweizhong,项目名称:ajaxnet,代码行数:54,代码来源:JavaScriptUtil.cs

示例14: Main

 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);
     }
 }
开发者ID:jieshan,项目名称:HRCSharp,代码行数:48,代码来源:MorganAndAString.cs

示例15: LoadMuiStringValue

		/// <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;
		}
开发者ID:amithasan,项目名称:Framework-Class-Library-Extension,代码行数:23,代码来源:Extensions.RegistryKey.cs


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