System.Text.StringBuilder.Replace(string, string)

Here are the examples of the csharp api System.Text.StringBuilder.Replace(string, string) taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

508 Examples 7

19 View Source File : SozlukDataStore.cs
License : MIT License
Project Creator : 0ffffffffh

private static string BuildFetchSQLQuery(
            ref string baseQueryHash,
            string content, 
            string suser, 
            DateTime begin, DateTime end,
            int rowBegin,int rowEnd)
        {
            bool linkAnd = false;
            string query;

            StringBuilder sb = new StringBuilder();
            StringBuilder cond = new StringBuilder();

            if (!CacheManager.TryGetCachedResult<string>(baseQueryHash, out query))
            {

                if (!string.IsNullOrEmpty(suser))
                    sb.AppendFormat(SEARCH_SUSER_ID_GET_SQL, suser.Trim());

                if (!string.IsNullOrEmpty(content))
                {
                    cond.AppendFormat(SEARCH_COND_CONTENT, content.Trim());
                    linkAnd = true;
                }

                if (!string.IsNullOrEmpty(suser))
                {
                    if (linkAnd)
                        cond.Append(" AND ");
                    else
                        linkAnd = true;

                    cond.Append(SEARCH_COND_SUSER);
                }

                if (begin != DateTime.MinValue && end != DateTime.MinValue)
                {
                    if (linkAnd)
                        cond.Append(" AND ");

                    cond.AppendFormat(SEARCH_COND_DATE, begin.ToString(), end.ToString());

                }

                sb.Append(SEARCH_SQL_BASE);

                if (cond.Length > 0)
                {
                    cond.Insert(0, "WHERE ");
                    sb.Replace("%%CONDITIONS%%", cond.ToString());
                }
                else
                {
                    sb.Replace("%%CONDITIONS%%", string.Empty);
                }

                if (!string.IsNullOrEmpty(content))
                    sb.Replace("%%COUNT_CONDITION%%", string.Format(SEARCH_COND_COUNT_CONTENT, content));
                else
                    sb.Replace("%%COUNT_CONDITION%%", SEARCH_COND_COUNT_ALL);


                if (!string.IsNullOrEmpty(suser))
                    sb.Append(" AND EntryCount > 0");

                sb.Append(";");

                baseQueryHash = Helper.Md5(sb.ToString());

                CacheManager.CacheObject(baseQueryHash, sb.ToString());
            }
            else
            {
                sb.Append(query);
            }

            sb.Replace("%%ROW_LIMIT_CONDITION%%",
                string.Format("RowNum BETWEEN {0} AND {1}", rowBegin, rowEnd));
            
            query = sb.ToString();

            cond.Clear();
            sb.Clear();

            cond = null;
            sb = null;

            return query;
        }

19 View Source File : JcApiHelperUIMiddleware.cs
License : MIT License
Project Creator : 279328316

private async Task RespondWithIndexHtml(HttpResponse response)
        {
            response.StatusCode = 200;
            response.ContentType = "text/html;charset=utf-8";

            using (Stream stream = apiHelperreplacedembly.GetManifestResourceStream($"{embeddedFileNamespace}.index.html"))
            {
                // Inject arguments before writing to response
                StringBuilder htmlBuilder = new StringBuilder(new StreamReader(stream).ReadToEnd());

                //处理index.html baseUrl 以兼容非根目录以及Nginx代理转发情况
                htmlBuilder.Replace("<base id=\"base\" href=\"/\">", $"<base id=\"base\" href=\"/ApiHelper/\">");
                await response.WriteAsync(htmlBuilder.ToString(), Encoding.UTF8);
            }
        }

19 View Source File : JsonWriter.cs
License : MIT License
Project Creator : 5minlab

public static string Filter(string val) {
            var sb = new StringBuilder(val);
            foreach (var t in tuples) {
                sb.Replace(t.prev, t.next);
            }
            return sb.ToString();
        }

19 View Source File : XmlFoldingStrategy.cs
License : MIT License
Project Creator : Abdesol

static string XmlEncodeAttributeValue(string attributeValue, char quoteChar)
		{
			StringBuilder encodedValue = new StringBuilder(attributeValue);

			encodedValue.Replace("&", "&");
			encodedValue.Replace("<", "<");
			encodedValue.Replace(">", ">");

			if (quoteChar == '"') {
				encodedValue.Replace("\"", """);
			} else {
				encodedValue.Replace("'", "'");
			}

			return encodedValue.ToString();
		}

19 View Source File : VBExpressionEditorSyntaxLanguage.cs
License : MIT License
Project Creator : Actipro

public string GetHeaderText(IEnumerable<ModelItem> variableModels) {
			// Inject namespace imports
			var headerText = new StringBuilder();
			headerText.AppendLine(@"Imports System
Imports System.Collections
Imports System.Collections.Generic
Imports System.Linq");

			// NOTE: Automated IntelliPrompt will only show for namespaces and types that are within the imported namespaces...
			//       Add other namespace imports here if types from other namespaces should be accessible

			// Inject a Clreplaced and Sub wrapper
			headerText.AppendLine();
			headerText.AppendLine(@"Shared Clreplaced Expression
Shared Sub ExpressionValue");

			// Append variable declarations so they appear in IntelliPrompt
			if (variableModels != null) {
				foreach (var variableModel in variableModels) {
					if (variableModel != null) {
						var variable = variableModel.GetCurrentValue() as LocationReference;
						if (variable != null) {
							// Build a VB representation of the variable's type name
							var variableTypeName = new StringBuilder();
							AppendTypeName(variableTypeName, variable.Type);

							headerText.Append("Dim ");
							headerText.Append(variable.Name);
							headerText.Append(" As ");
							headerText.Append(variableTypeName.Replace("[", "(").Replace("]", ")"));
							headerText.AppendLine();
						}
					}
				}
			}

			// Since the doreplacedent text is an expression, inject a Return statement start at the end of the header text
			headerText.AppendLine();
			headerText.Append("Return ");

			return headerText.ToString();
		}

19 View Source File : AddressCompositeControlTemplate.cs
License : MIT License
Project Creator : Adoxio

private IEnumerable<Control> MakeEditControls(string fieldName, string labelName)
		{
			var fieldMetaData = this.enreplacedyMetadata.Attributes.FirstOrDefault(a => a.LogicalName == this.alias + fieldName);

			var controls = new List<Control>();
			var textBox = new TextBox
			{
				ID = string.Concat(this.ControlID, fieldName),
				CssClreplaced = string.Concat(" content ", " ", this.CssClreplaced, this.Metadata.CssClreplaced),
				ToolTip = this.Metadata.ToolTip
			};

			var snippetName = "AddressCompositeControlTemplate/FieldLabel/" + labelName;

			var fieldLabelSnippet = new WebControls.Snippet
			{
				SnippetName = snippetName,
				DisplayName = snippetName,
				EditType = "text",
				Editable = true,
				DefaultText = ResourceManager.GetString(labelName),
				HtmlTag = HtmlTextWriterTag.Label
			};
			
			if (this.isEditable)
			{
				// Applying required parameters to first name if it's application required
				if (fieldMetaData != null
					&& (fieldMetaData.RequiredLevel.Value == AttributeRequiredLevel.ApplicationRequired
						|| fieldMetaData.RequiredLevel.Value == AttributeRequiredLevel.SystemRequired))
				{
					textBox.Attributes.Add("required", string.Empty);
					var requierdContainer = new HtmlGenericControl("div");
					requierdContainer.Attributes["clreplaced"] = "info required";
					requierdContainer.Controls.Add(fieldLabelSnippet);
					controls.Add(requierdContainer);
				}
				else
				{
					controls.Add(fieldLabelSnippet);
				}
			}
			controls.Add(textBox);
			textBox.Attributes.Add("onchange", "setIsDirty(this.id);");
			this.Bindings[this.ControlID + this.alias + fieldName] = new CellBinding
			{
				Get = () =>
				{
					var str = textBox.Text;
					return str != null ? str.Replace("\r\n", "\n") : string.Empty;
				},
				Set = obj =>
				{
					var enreplacedy = obj as Enreplacedy;

					if (enreplacedy != null)
					{
						textBox.Text =
							enreplacedy.GetAttributeValue<string>(
								this.alias + fieldName);
					}
				}
			};
			this.bindControlValue.Add(enreplacedy =>
			{
				this.addressControlValue.Replace("{" + textBox.ID + "}", enreplacedy.GetAttributeValue<string>(this.alias + fieldName));
			});
			return controls;
		}

19 View Source File : StringHelper.cs
License : Mozilla Public License 2.0
Project Creator : agebullhu

public static string MulitReplace(this string str, params string[] rs)
        {
            if (str == null || rs == null || rs.Length == 0)
                return str;
            var sb = new StringBuilder(str);
            for (var i = 0; i < rs.Length; i += 2)
                sb.Replace(rs[i], rs[i + 1]);
            return sb.ToString();
        }

19 View Source File : StringHelper.cs
License : Mozilla Public License 2.0
Project Creator : agebullhu

public static string MulitReplace2(this string str, string last, params string[] org)
        {
            if (str == null || org == null || org.Length == 0)
                return str;
            var sb = new StringBuilder(str);
            for (var i = 0; i < org.Length; i += 1)
                sb.Replace(org[i], last);
            return sb.ToString();
        }

19 View Source File : NpcSpawnHelper.cs
License : GNU General Public License v3.0
Project Creator : AHeroicLlama

public static string TrimNPCName(string name)
		{
			// Drop the plurals
			if (name.EndsWith("s"))
			{
				name = name.Remove(name.Length - 1);
			}

			// Drop the ESSChance prefix
			name = new StringBuilder(name)
			.Replace("ESSChanceSub", string.Empty)
			.Replace("ESSChanceMain", string.Empty)

			// Drop the editor labels
			.Replace("LARGE", string.Empty)
			.Replace("GIANTONLY", string.Empty)

			// Convert names
			.Replace("Rat", "Rad Rat")
			.Replace("Toad", "Rad Toad")
			.Replace("RadAnt", "Rad Ant")
			.Replace("Scorpions", "Rad Scorpion")
			.Replace("MoleMiner", "Mole Miner")
			.Replace("ViciousDog", "Vicious Dog")
			.Replace("SuperMutant", "Super Mutant")
			.Replace("Megasloth", "Mega Sloth")
			.Replace("Molerat", "Mole Rat")
			.Replace("YaoGuai", "Yao Guai")
			.Replace("FogCrawler", "Fog Crawler")
			.Replace("HoneyBeast", "Honey Beast")
			.Replace("CaveCricket", "Cave Cricket")
			.Replace("Mutations", "Snallygaster")
			.Replace("GraftonMonster", "Grafton Monster")
			.ToString();

			return name;
		}

19 View Source File : SourceFormat.cs
License : GNU General Public License v3.0
Project Creator : ahmed605

private string FormatCode(string source, bool lineNumbers, 
			bool alternate, bool embedStyleSheet, bool subCode)
		{
			//replace special characters
			StringBuilder sb = new StringBuilder(source);

			if(!subCode)
			{
				sb.Replace("&", "&");
				sb.Replace("<", "<");
				sb.Replace(">", ">");
				sb.Replace("\t", string.Empty.PadRight(_tabSpaces));
			}
			
			//color the code
			source = codeRegex.Replace(sb.ToString(), new MatchEvaluator(this.MatchEval));

			sb = new StringBuilder();
			
			if (embedStyleSheet)
			{
				sb.Append("<style type=\"text/css\">\n");
				sb.Append(GetCssString());
				sb.Append("</style>\n");
			}

			if (lineNumbers || alternate) //we have to process the code line by line
			{
				if(!subCode)
					sb.Append("<div clreplaced=\"csharpcode\">\n");
				StringReader reader = new StringReader(source);
				int i = 0;
				string spaces = "    ";
				int order;
				string line;
				while ((line = reader.ReadLine()) != null)
				{
					i++;
					if (alternate && ((i % 2) == 1))
					{
						sb.Append("<pre clreplaced=\"alt\">");
					}
					else
					{
						sb.Append("<pre>");
					}

					if(lineNumbers)
					{
						order = (int)Math.Log10(i);
						sb.Append("<span clreplaced=\"lnum\">" 
							+ spaces.Substring(0, 3 - order) + i.ToString() 
							+ ":  </span>");
					}
					
					if(line.Length == 0)
						sb.Append(" ");
					else
						sb.Append(line);
					sb.Append("</pre>\n");
				}
				reader.Close();
				if(!subCode)
					sb.Append("</div>");
			}
			else
			{
				//have to use a <pre> because IE below ver 6 does not understand 
				//the "white-space: pre" CSS value
				if(!subCode)
					sb.Append("<pre clreplaced=\"csharpcode\">\n");
				sb.Append(source);
				if(!subCode)
					sb.Append("</pre>");
			}
			
			return sb.ToString();
		}

19 View Source File : Toolbox.cs
License : GNU General Public License v3.0
Project Creator : akaAgar

internal static string ReplaceAll(this string str, string replaceTo, params string[] replaceFrom)
        {
            StringBuilder sb = new StringBuilder(str);
            
            foreach (string r in replaceFrom)
                sb.Replace(r, replaceTo);

            return sb.ToString();
        }

19 View Source File : AssetTreeModel.cs
License : MIT License
Project Creator : akof1314

public void ThreadPoolCallback(System.Object threadContext)
            {
                try
                {
                    string text = File.ReadAllText(m_Path);

                    // 搜索
                    if (string.IsNullOrEmpty(m_ReplaceStr))
                    {
                        for (int i = 0; i < m_Patterns.Count; i++)
                        {
                            if (text.Contains(m_Patterns[i]))
                            {
                                m_SearchRet[i] = true;
                            }
                        }
                    }
                    else
                    {
                        StringBuilder sb = new StringBuilder(text, text.Length * 2);
                        foreach (var pattern in m_Patterns)
                        {
                            sb.Replace(pattern, m_ReplaceStr);
                        }

                        string text2 = sb.ToString();
                        if (!string.Equals(text, text2))
                        {
                            File.WriteAllText(m_Path, text2);
                        }
                    }
                }
                catch (Exception ex)
                {
                    exception = m_Path + "\n" + ex.Message;
                }

                doneEvent.Set();
            }

19 View Source File : WorkItemManger.cs
License : MIT License
Project Creator : alkampfergit

public List<WorkItem> ExecuteQuery(string wiqlQuery)
        {
            StringBuilder query = new StringBuilder();
            query.AppendLine(wiqlQuery);
            if (!String.IsNullOrEmpty(_teamProjectName))
            {
                query = query.Replace("{teamProjectName}", _teamProjectName);
            }

            try
            {
                var realQuery = query.ToString();
                Log.Information("About to execute query {query}", realQuery);

                if (!realQuery.Contains("workitemLinks"))
                {
                    return _connection.WorkItemStore.Query(realQuery)
                        .OfType<WorkItem>()
                        .ToList();
                }
                return ExecuteLinkedQuery(realQuery);
            }
            catch (Exception ex)
            {
                Log.Error(ex, "Error executing Query [{message}]\n{query}", ex.Message, query.ToString());
                throw;
            }
        }

19 View Source File : ACML.cs
License : MIT License
Project Creator : allisterb

public override bool CleanAndFixup()
        {
            if (!base.CleanAndFixup())
            {
                return false;
            }
            
            string s = File.ReadAllText(F);
            StringBuilder sb = new StringBuilder(s);
            if (s.Contains($" *(global::{Module.OutputNamespace}.MKL_Complex8.__Internal*) "))
            {
                sb.Replace($" *(global::{Module.OutputNamespace}.MKL_Complex8.__Internal*) ", string.Empty);
            }
            if (s.Contains($" *(global::{Module.OutputNamespace}.MKL_Complex16.__Internal*) "))
            {
                sb.Replace($" *(global::{Module.OutputNamespace}.MKL_Complex16.__Internal*) ", string.Empty);
            }
            if (s.Contains($" *(global::{Module.OutputNamespace}.MKLVersion.__Internal*) "))
            {
                sb.Replace($" *(global::{Module.OutputNamespace}.MKLVersion.__Internal*) ", string.Empty);
            }
            File.WriteAllText(F, sb.ToString());
            return true;
        }

19 View Source File : CUDA.cs
License : MIT License
Project Creator : allisterb

public override bool CleanAndFixup()
        {
            if (!base.CleanAndFixup())
            {
                return false;
            }           
            string s = File.ReadAllText(F);
            StringBuilder sb = new StringBuilder(s);
            if (s.Contains($"return ((global::{this.Namespace}.CudaLaunchParams.__Internal*) __Instance)->args;"))
            {
                sb.Replace($"return ((global::{this.Namespace}.CudaLaunchParams.__Internal*) __Instance)->args;", $"return (void**) ((global::{this.Namespace}.CudaLaunchParams.__Internal*) __Instance)->args;");
            }
            if (s.Contains("DllImport(\"cublas\""))
            {
                sb.Replace("DllImport(\"cublas\"", "DllImport(\"cublas64_91\"");
            }
            if (s.Contains("DllImport(\"cudart\""))
            {
                sb.Replace("DllImport(\"cudart\"", "DllImport(\"cudart64_91\"");
            }
            File.WriteAllText(F, sb.ToString());
            return true;
        }

19 View Source File : JemApi.cs
License : MIT License
Project Creator : allisterb

public static string GetMallocStats(string opt)
        {
            StringBuilder statsBuilder = new StringBuilder(1000);
            __Internal.JeMallocMessageCallback stats = (o, m) => { statsBuilder.Append(m); };
            __Internal.JeMallocStatsPrint(Marshal.GetFunctionPointerForDelegate(stats), IntPtr.Zero, opt);
            if (Environment.OSVersion.Platform == PlatformID.Win32NT)
            {
                statsBuilder = statsBuilder.Replace("\\n", "\\r\\n");
            }
            return statsBuilder.ToString();
        }

19 View Source File : PrivoxyController.cs
License : MIT License
Project Creator : AmazingDM

public bool Start(Server server, Mode mode)
        {
            var text = new StringBuilder(File.ReadAllText("bin\\default.conf"));

            text.Replace("_BIND_PORT_", Global.Settings.HTTPLocalPort.ToString());
            text.Replace("0.0.0.0", Global.Settings.LocalAddress); /* BIND_HOST */

            if (server is Socks5 socks5 && !socks5.Auth())
            {
                text.Replace("/ 127.0.0.1", $"/ {server.AutoResolveHostname()}"); /* DEST_HOST */
                text.Replace("_DEST_PORT_", socks5.Port.ToString());
            }

            text.Replace("_DEST_PORT_", Global.Settings.Socks5LocalPort.ToString());


            File.WriteAllText("data\\privoxy.conf", text.ToString());

            return StartInstanceAuto("..\\data\\privoxy.conf");
        }

19 View Source File : TCPSink.cs
License : Apache License 2.0
Project Creator : anjoy8

public void Emit(LogEvent logEvent)
        {
            var sb = new StringBuilder();

            using (var sw = new StringWriter(sb))
                _formatter.Format(logEvent, sw);

            sb.Replace("RenderedMessage", "message");
            _socketWriter.Enqueue(sb.ToString());
        }

19 View Source File : UDPSink.cs
License : Apache License 2.0
Project Creator : anjoy8

public void Emit(LogEvent logEvent)
        {
            var sb = new StringBuilder();

            using (var sw = new StringWriter(sb))
                _formatter.Format(logEvent, sw);

            sb.Replace("RenderedMessage", "message");

            _socket.Send(Encoding.UTF8.GetBytes(sb.ToString()));
        }

19 View Source File : RomaConvert.cs
License : Apache License 2.0
Project Creator : AnkiUniversal

public static string ConvertRomaToHiraFullLoop(string text)
        {
            StringBuilder builder = new StringBuilder(text);
            for(int i = START_SILENT__INDEX; i <= END_SILENT_INDEX; i ++)
            {
                builder.Replace(HiraRomaKata[i, ROMAJI], HiraRomaKata[i, HIRAGANA]);
            }
            for (int i = 0; i < START_SILENT__INDEX; i++)
            {
                builder.Replace(HiraRomaKata[i, ROMAJI], HiraRomaKata[i, HIRAGANA]);
            }
            return builder.ToString();        
        }

19 View Source File : RomaConvert.cs
License : Apache License 2.0
Project Creator : AnkiUniversal

public static string ConvertHiraToRomaFullLoop(StringBuilder builder)
        {
            for (int i = 0; i < NUMBER_OF_WORD; i++)
            {
                builder.Replace(HiraRomaKata[i, HIRAGANA], HiraRomaKata[i, ROMAJI]);
            }            
            builder.Replace("っ", " ");
            return builder.ToString();
        }

19 View Source File : RomaConvert.cs
License : Apache License 2.0
Project Creator : AnkiUniversal

public static string ConvertKataToRomaFullLoop(StringBuilder builder)
        {
            for (int i = 0; i < NUMBER_OF_WORD; i++)
            {
                builder.Replace(HiraRomaKata[i, KATAKANA], HiraRomaKata[i, ROMAJI]);
            }
            builder.Replace("ッ", " ");
            string results = builder.ToString();

            if (results.Contains('ー'))
            {
                return results.Replace('ー', '-');
            }
            else
                return results;
        }

19 View Source File : Settings.cs
License : BSD 3-Clause "New" or "Revised" License
Project Creator : anoyetta

public void Save()
        {
            lock (this.locker)
            {
                if (!this.isLoaded)
                {
                    return;
                }

                var directoryName = Path.GetDirectoryName(this.FileName);

                if (!Directory.Exists(directoryName))
                {
                    Directory.CreateDirectory(directoryName);
                }

                var ns = new XmlSerializerNamespaces();
                ns.Add(string.Empty, string.Empty);

                var buffer = new StringBuilder();
                using (var sw = new StringWriter(buffer))
                {
                    var xs = new XmlSerializer(this.GetType());
                    xs.Serialize(sw, this, ns);
                }

                buffer.Replace("utf-16", "utf-8");

                File.WriteAllText(
                    this.FileName,
                    buffer.ToString() + Environment.NewLine,
                    DefaultEncoding);
            }
        }

19 View Source File : SpellPanelTable.cs
License : BSD 3-Clause "New" or "Revised" License
Project Creator : anoyetta

public void Save()
        {
            lock (this)
            {
                if (this.table == null ||
                    this.table.Count < 1)
                {
                    return;
                }

                var dir = Path.GetDirectoryName(this.DefaultFile);

                if (!Directory.Exists(dir))
                {
                    Directory.CreateDirectory(dir);
                }

                var ns = new XmlSerializerNamespaces();
                ns.Add(string.Empty, string.Empty);

                var sb = new StringBuilder();
                using (var sw = new StringWriter(sb))
                {
                    var xs = new XmlSerializer(this.table.GetType());
                    xs.Serialize(sw, this.table, ns);
                }

                sb.Replace("utf-16", "utf-8");

                File.WriteAllText(
                    this.DefaultFile,
                    sb.ToString() + Environment.NewLine,
                    DefaultEncoding);
            }
        }

19 View Source File : SpellTable.cs
License : BSD 3-Clause "New" or "Revised" License
Project Creator : anoyetta

private void Save(
            string file,
            List<Spell> list)
        {
            var dir = Path.GetDirectoryName(file);
            if (!Directory.Exists(dir))
            {
                Directory.CreateDirectory(dir);
            }

            var ns = new XmlSerializerNamespaces();
            ns.Add(string.Empty, string.Empty);

            var sb = new StringBuilder();
            using (var sw = new StringWriter(sb))
            {
                var xs = new XmlSerializer(list.GetType());
                xs.Serialize(sw, list, ns);
            }

            sb.Replace("utf-16", "utf-8");

            File.WriteAllText(
                file,
                sb.ToString() + Environment.NewLine,
                DefaultEncoding);
        }

19 View Source File : TickerTable.cs
License : BSD 3-Clause "New" or "Revised" License
Project Creator : anoyetta

private void Save(
            string file,
            IList<Ticker> list)
        {
            var dir = Path.GetDirectoryName(file);
            if (!Directory.Exists(dir))
            {
                Directory.CreateDirectory(dir);
            }

            var ns = new XmlSerializerNamespaces();
            ns.Add(string.Empty, string.Empty);

            var sb = new StringBuilder();
            using (var sw = new StringWriter(sb))
            {
                var xs = new XmlSerializer(list.GetType());
                xs.Serialize(sw, list, ns);
            }

            sb.Replace("utf-16", "utf-8");

            File.WriteAllText(
                file,
                sb.ToString() + Environment.NewLine,
                DefaultEncoding);
        }

19 View Source File : TimelineSettings.cs
License : BSD 3-Clause "New" or "Revised" License
Project Creator : anoyetta

public void Save(
            string file)
        {
            if (this.isSaving)
            {
                return;
            }

            try
            {
                this.isSaving = true;
            }
            finally
            {
                lock (Locker)
                {
                    FileHelper.CreateDirectory(file);

                    var ns = new XmlSerializerNamespaces();
                    ns.Add(string.Empty, string.Empty);

                    var buffer = new StringBuilder();
                    using (var sw = new StringWriter(buffer))
                    {
                        var xs = new XmlSerializer(this.GetType());
                        xs.Serialize(sw, this, ns);
                    }

                    buffer.Replace("utf-16", "utf-8");

                    using (var sw = new StreamWriter(file, false, new UTF8Encoding(false)))
                    {
                        sw.Write(buffer.ToString() + Environment.NewLine);
                        sw.Flush();
                    }
                }

                this.isSaving = false;
            }
        }

19 View Source File : ConditionUtility.cs
License : BSD 3-Clause "New" or "Revised" License
Project Creator : anoyetta

private static int ReplaceMessageWithSpell(
            StringBuilder message,
            Guid[] timers,
            int baseIndex)
        {
            int count = 0;

            for (int i = 0; i < timers.Length; i++)
            {
                var spell = SpellTable.Instance.GetSpellTimerByGuid(timers[i]);
                if (spell != null)
                {
                    count++;

                    if (spell.RegexEnabled && spell.Regex != null && spell.MatchedLog != string.Empty)
                    {
                        foreach (Match match in spell.Regex.Matches(spell.MatchedLog))
                        {
                            foreach (var number in spell.Regex.GetGroupNumbers())
                            {
                                message.Replace(String.Format("$C{0}-{1}", (baseIndex + i), number), match.Groups[number].Value);
                            }
                        }
                    }
                }
            }

            return count;
        }

19 View Source File : ConditionUtility.cs
License : BSD 3-Clause "New" or "Revised" License
Project Creator : anoyetta

private static int ReplaceMessageWithTelop(
            StringBuilder message,
            Guid[] timers,
            int baseIndex)
        {
            int count = 0;

            for (int i = 0; i < timers.Length; i++)
            {
                var telop = TickerTable.Instance.GetOnePointTelopByGuid(timers[i]);
                if (telop != null)
                {
                    count++;

                    if (telop != null && telop.RegexEnabled && telop.Regex != null && !string.IsNullOrEmpty(telop.MatchedLog))
                    {
                        foreach (Match match in telop.Regex.Matches(telop.MatchedLog))
                        {
                            foreach (var number in telop.Regex.GetGroupNumbers())
                            {
                                message.Replace(String.Format("$C{0}-{1}", (baseIndex + i), number), match.Groups[number].Value);
                            }
                        }
                    }
                }
            }

            return count;
        }

19 View Source File : ExportContainer.cs
License : BSD 3-Clause "New" or "Revised" License
Project Creator : anoyetta

public void Save(
            string file)
        {
            var dir = Path.GetDirectoryName(file);

            if (!Directory.Exists(dir))
            {
                Directory.CreateDirectory(dir);
            }

            var ns = new XmlSerializerNamespaces();
            ns.Add(string.Empty, string.Empty);

            var sb = new StringBuilder();
            using (var sw = new StringWriter(sb))
            {
                var xs = new XmlSerializer(this.GetType());
                xs.Serialize(sw, this, ns);
            }

            sb.Replace("utf-16", "utf-8");

            File.WriteAllText(
                file,
                sb.ToString(),
                new UTF8Encoding(false));
        }

19 View Source File : Settings.cs
License : BSD 3-Clause "New" or "Revised" License
Project Creator : anoyetta

public void Save()
        {
            lock (lockObject)
            {
                var file = FilePath;

                var dir = Path.GetDirectoryName(file);

                if (!Directory.Exists(dir))
                {
                    Directory.CreateDirectory(dir);
                }

                // ステータスアラートの対象を初期化する
                this.StatusAlertSettings.SetDefaultAlertTargets();

                var ns = new XmlSerializerNamespaces();
                ns.Add(string.Empty, string.Empty);

                var buffer = new StringBuilder();
                using (var sw = new StringWriter(buffer))
                {
                    var xs = new XmlSerializer(typeof(Settings));
                    xs.Serialize(sw, Default, ns);
                }

                buffer.Replace("utf-16", "utf-8");

                File.WriteAllText(
                    file,
                    buffer.ToString() + Environment.NewLine,
                    DefaultEncoding);
            }
        }

19 View Source File : Settings.cs
License : BSD 3-Clause "New" or "Revised" License
Project Creator : anoyetta

public void Load()
        {
            var utf8 = new UTF8Encoding(false);

            lock (locker)
            {
                var file = this.FileName;
                if (!File.Exists(file))
                {
                    this.Reset();
                    this.Save();
                    return;
                }

                var fi = new FileInfo(file);
                if (fi.Length <= 0)
                {
                    this.Reset();
                    this.Save();
                    return;
                }

                // typo を置換する
                var text = new StringBuilder(File.ReadAllText(file, utf8));
                text.Replace("Avalable", "Available");
                File.WriteAllText(file, text.ToString(), utf8);

                using (var xr = XmlReader.Create(file))
                {
                    var data = this.Serializer.Deserialize(xr) as Settings;
                    if (data != null)
                    {
                        this.Migrate(data);
                        instance = data;
                    }
                }
            }
        }

19 View Source File : TimelineModel.cs
License : BSD 3-Clause "New" or "Revised" License
Project Creator : anoyetta

public void Save(
            string file)
        {
            lock (this)
            {
                FileHelper.CreateDirectory(file);

                var ns = new XmlSerializerNamespaces();
                ns.Add(string.Empty, string.Empty);

                var sb = new StringBuilder();
                using (var sw = new StringWriter(sb))
                {
                    var xs = new XmlSerializer(this.GetType());
                    xs.Serialize(sw, this, ns);
                }

                sb.Replace("utf-16", "utf-8");
                sb.Replace("True", "true");
                sb.Replace("False", "false");

                var text = sb.ToString();
                text = TimelineTagRegex.Replace(text, "<timeline>");

                File.WriteAllText(
                    file,
                    text + Environment.NewLine,
                    new UTF8Encoding(false));
            }
        }

19 View Source File : ITrigger.cs
License : BSD 3-Clause "New" or "Revised" License
Project Creator : anoyetta

public static Task<string> ToXMLAsync(
            this ITrigger t)
            => Task.Run(() =>
            {
                if (t == null)
                {
                    return string.Empty;
                }

                var xws = new XmlWriterSettings()
                {
                    OmitXmlDeclaration = true,
                    Indent = true,
                };

                var ns = new XmlSerializerNamespaces();
                ns.Add(string.Empty, string.Empty);

                var sb = new StringBuilder();
                using (var xw = XmlWriter.Create(sb, xws))
                {
                    var xs = new XmlSerializer(t.GetType());
                    WPFHelper.Invoke(() => xs.Serialize(xw, t, ns));
                }

                sb.Replace("utf-16", "utf-8");

                return sb.ToString() + Environment.NewLine;
            });

19 View Source File : TagTable.cs
License : BSD 3-Clause "New" or "Revised" License
Project Creator : anoyetta

public void Save()
        {
            lock (this)
            {
                if (!this.isLoaded)
                {
                    return;
                }

                var file = this.DefaultFile;

                FileHelper.CreateDirectory(file);

                var ns = new XmlSerializerNamespaces();
                ns.Add(string.Empty, string.Empty);

                var sb = new StringBuilder();
                using (var sw = new StringWriter(sb))
                {
                    var xs = new XmlSerializer(this.GetType());
                    xs.Serialize(sw, this, ns);
                }

                sb.Replace("utf-16", "utf-8");

                File.WriteAllText(
                    file,
                    sb.ToString() + Environment.NewLine,
                    DefaultEncoding);
            }
        }

19 View Source File : Settings.cs
License : BSD 3-Clause "New" or "Revised" License
Project Creator : anoyetta

public void Save()
        {
            lock (locker)
            {
                if (!Directory.Exists(Path.GetDirectoryName(this.FileName)))
                {
                    Directory.CreateDirectory(Path.GetDirectoryName(this.FileName));
                }

                // MPTickerのジョブリストが欠けていたら補完する
                var missingJobs = DefaultMPTickerTargetJobs.Where(x =>
                    !this.MPTicker.TargetJobs.Any(y => y.Job == x.Job));
                if (missingJobs.Any())
                {
                    this.MPTicker.TargetJobs.AddRange(missingJobs);
                }

                var ns = new XmlSerializerNamespaces();
                ns.Add(string.Empty, string.Empty);

                var buffer = new StringBuilder();
                using (var sw = new StringWriter(buffer))
                using (var xw = XmlWriter.Create(sw, this.XmlWriterSettings))
                {
                    this.Serializer.Serialize(xw, instance, ns);
                }

                buffer.Replace("utf-16", "utf-8");

                File.WriteAllText(
                    this.FileName,
                    buffer.ToString() + Environment.NewLine,
                    DefaultEncoding);
            }
        }

19 View Source File : Config.cs
License : BSD 3-Clause "New" or "Revised" License
Project Creator : anoyetta

public static void Save()
        {
            lock (Locker)
            {
                if (isInitializing)
                {
                    return;
                }

                var directoryName = Path.GetDirectoryName(FileName);

                if (!Directory.Exists(directoryName))
                {
                    Directory.CreateDirectory(directoryName);
                }

                var ns = new XmlSerializerNamespaces();
                ns.Add(string.Empty, string.Empty);

                var sb = new StringBuilder();
                using (var sw = new StringWriter(sb))
                {
                    var xs = new XmlSerializer(instance.GetType());
                    xs.Serialize(sw, instance, ns);
                }

                sb.Replace("utf-16", "utf-8");

                File.WriteAllText(
                    FileName,
                    sb.ToString(),
                    new UTF8Encoding(false));
            }
        }

19 View Source File : Config.cs
License : BSD 3-Clause "New" or "Revised" License
Project Creator : anoyetta

public static void Save()
        {
            lock (ConfigBlocker)
            {
                if (instance == null)
                {
                    return;
                }

                var now = DateTime.Now;
                if ((now - lastSaveTimestamp).TotalSeconds < 5)
                {
                    return;
                }

                var directoryName = Path.GetDirectoryName(FileName);

                if (!Directory.Exists(directoryName))
                {
                    Directory.CreateDirectory(directoryName);
                }

                var ns = new XmlSerializerNamespaces();
                ns.Add(string.Empty, string.Empty);

                var sb = new StringBuilder();
                using (var sw = new StringWriter(sb))
                {
                    var xs = new XmlSerializer(instance.GetType());
                    xs.Serialize(sw, instance, ns);
                }

                sb.Replace("utf-16", "utf-8");

                File.WriteAllText(
                    FileName,
                    sb.ToString() + Environment.NewLine,
                    DefaultEncoding);

                lastSaveTimestamp = now;
            }
        }

19 View Source File : ReleaseNotes.cs
License : MIT License
Project Creator : anoyetta

public string Serialize()
        {
            var ns = new XmlSerializerNamespaces();
            ns.Add(string.Empty, string.Empty);

            var sb = new StringBuilder();
            using (var sw = new StringWriter(sb))
            using (var xw = XmlWriter.Create(sw, new XmlWriterSettings()
            {
                OmitXmlDeclaration = true,
                Indent = true,
                NewLineHandling = NewLineHandling.None,
                NewLineOnAttributes = true,
            }))
            {
                var xs = new XmlSerializer(this.GetType());
                xs.Serialize(xw, this, ns);
            }

            sb.Replace("utf-16", "utf-8");

            return sb.ToString();
        }

19 View Source File : Config.cs
License : BSD 3-Clause "New" or "Revised" License
Project Creator : anoyetta

public void Save(
            string fileName)
        {
            lock (this)
            {
                var directoryName = Path.GetDirectoryName(fileName);

                if (!Directory.Exists(directoryName))
                {
                    Directory.CreateDirectory(directoryName);
                }

                var ns = new XmlSerializerNamespaces();
                ns.Add(string.Empty, string.Empty);

                var buffer = new StringBuilder();
                using (var sw = new StringWriter(buffer))
                {
                    var xs = new XmlSerializer(this.GetType());
                    xs.Serialize(sw, this, ns);
                }

                buffer.Replace("utf-16", "utf-8");

                File.WriteAllText(
                    fileName,
                    buffer.ToString() + Environment.NewLine,
                    DefaultEncoding);
            }
        }

19 View Source File : Notes.cs
License : MIT License
Project Creator : anoyetta

public void Save(
            string fileName)
        {
            lock (this)
            {
                var dir = Path.GetDirectoryName(FileName);
                if (!Directory.Exists(dir))
                {
                    Directory.CreateDirectory(dir);
                }

                var ns = new XmlSerializerNamespaces();
                ns.Add(string.Empty, string.Empty);

                var sb = new StringBuilder();
                using (var sw = new StringWriter(sb))
                {
                    NotesSerializer.Serialize(sw, this.NoteList, ns);
                }

                sb.Replace("utf-16", "utf-8");

                File.WriteAllText(
                    fileName,
                    sb.ToString() + Environment.NewLine,
                    new UTF8Encoding(false));
            }
        }

19 View Source File : GtkStylePreviewGenerator.cs
License : MIT License
Project Creator : arcusmaximus

private static string GetSpanMarkup(StringBuilder css, string text)
        {
            return new XElement(
                "span",
                new XAttribute("css", css.Replace("\r\n", "")),
                text
            ).ToString();
        }

19 View Source File : SaveWriter.cs
License : MIT License
Project Creator : Arkhist

[HarmonyPrefix]
        [HarmonyPatch(typeof(OS), nameof(OS.writeSaveGame))]
        internal static bool SaveWriteReplacementPrefix(ref OS __instance, string filename)
        {
            var settings = new XmlWriterSettings
            {
                Indent = true
            };
            var builder = new StringBuilder();
            
            using (var writer = XmlWriter.Create(builder, settings))
            {
                var saveElement = GetHacknetSaveElement(__instance);
                saveElement.Add(GetDLCSaveElement(__instance));
                saveElement.Add(GetFlagsSaveElement(__instance.Flags));
                saveElement.Add(GetNetmapSaveElement(__instance.netMap));
                saveElement.Add(GetMissionSaveElement(__instance.currentMission));

                var branchMissionsTag = new XElement("branchMissions");
                foreach (var branch in __instance.branchMissions)
                    branchMissionsTag.Add(GetMissionSaveElement(branch));

                saveElement.Add(branchMissionsTag);

                saveElement.Add(GetAllFactionsSaveElement(__instance.allFactions));
                
                var otherTag = new XElement("other");
                otherTag.SetAttributeValue("music", MusicManager.currentSongName);
                otherTag.SetAttributeValue("homeNode", __instance.homeNodeID);
                otherTag.SetAttributeValue("homereplacedetsNode", __instance.homereplacedetServerID);
                saveElement.Add(otherTag);

                EventManager<SaveEvent>.InvokeAll(new SaveEvent(__instance, saveElement, filename));
                
                writer.WriteStartDoreplacedent();
                
                saveElement.WriteTo(writer);

                writer.WriteEndDoreplacedent();
            }
            
            SaveFileManager.WriteSaveData(builder.Replace("\t", "  ").ToString(), filename);

            return false;
        }

19 View Source File : ElementInfo.cs
License : MIT License
Project Creator : Arkhist

public override string ToString()
        {
            var builder = new StringBuilder();
            var settings = new XmlWriterSettings
            {
                Indent = true
            };
            using (var writer = XmlWriter.Create(builder, settings))
            {
                WriteToXML(writer);
            }

            return builder.Replace("\t", "  ").ToString();
        }

19 View Source File : FormattedText.cs
License : GNU General Public License v3.0
Project Creator : arklumpus

private static Tags GetTag(string text, int start, out int tagEnd, out Brush tagBrush)
        {
            StringBuilder tag = new StringBuilder();
            bool closed = false;

            int i = start;

            for (; i < text.Length; i++)
            {
                tag.Append(text[i]);

                if (text[i] == '>')
                {
                    closed = true;
                    break;
                }
            }

            tagEnd = i;
            tagBrush = null;

            if (!closed)
            {
                return Tags.None;
            }
            else
            {
                string tagString = tag.Replace(" ", "").ToString().ToLowerInvariant();

                if (tagString == "<b>" || tagString == "<strong>")
                {
                    return Tags.BoldOpen;
                }
                else if (tagString == "</b>" || tagString == "</strong>")
                {
                    return Tags.BoldClose;

                }
                else if (tagString == "<i>" || tagString == "<em>")
                {
                    return Tags.ItalicsOpen;
                }
                else if (tagString == "</i>" || tagString == "</em>")
                {
                    return Tags.ItalicsClose;
                }
                else if (tagString == "<sup>")
                {
                    return Tags.SupOpen;
                }
                else if (tagString == "</sup>")
                {
                    return Tags.SupClose;
                }
                else if (tagString == "<sub>")
                {
                    return Tags.SubOpen;
                }
                else if (tagString == "</sub>")
                {
                    return Tags.SubClose;
                }
                else if (tagString.StartsWith("<#"))
                {
                    string colour = tagString.Substring(1, tagString.Length - 2);

                    Colour? col = null;

                    try
                    {
                        col = Colour.FromCSSString(colour);
                    }
                    catch { }

                    if (col == null)
                    {
                        colour = tagString.Substring(2, tagString.Length - 3);

                        col = Colour.FromCSSString(colour);
                    }

                    if (col != null)
                    {
                        tagBrush = col.Value;
                        return Tags.ColourOpen;
                    }
                    else
                    {
                        return Tags.None;
                    }
                }
                else if (tagString == "</#>")
                {
                    return Tags.ColourClose;
                }
                else
                {
                    return Tags.None;
                }
            }
        }

19 View Source File : FormatHelper.cs
License : GNU General Public License v3.0
Project Creator : armandoalonso

public string JsonCompress(string json, bool wrap = false)
        {
            if (wrap)
            {
                var returnString = $"{{{json}}}";
                returnString = returnString.Remove(0, 1);
                returnString = returnString.Remove(returnString.Length - 1, 1);
                var sb = new StringBuilder(returnString);
                sb.Replace("\t", string.Empty);
                sb.Replace("\n", string.Empty);
                sb.Replace("\r", string.Empty);
                sb.Replace(" ", string.Empty);
                return sb.ToString();
            }
            else
            {
                var sb = new StringBuilder(json);
                sb.Replace("\t", string.Empty);
                sb.Replace("\n", string.Empty);
                sb.Replace("\r", string.Empty);
                sb.Replace(" ", string.Empty);
                return sb.ToString();
            }
        }

19 View Source File : AntlrPostProcessor.cs
License : MIT License
Project Creator : asc-community

private static void ProcessFile(string path)
        {
            var finalPath = Path.Combine(ANTLR_PATH, path);

            var textSb = new StringBuilder(File.ReadAllText(finalPath));
            textSb.Replace("public sealed clreplaced", "internal clreplaced");
            textSb.Replace("public partial clreplaced", "internal partial clreplaced");
            textSb.Replace("public interface", "internal interface");
            File.WriteAllText(finalPath, textSb.ToString());
        }

19 View Source File : SourceGenerator.cs
License : MIT License
Project Creator : asc-community

public string Generate(params string[] replacements)
        { 
            if (replacements.Length != toReplace.Length)
                throw new ArgumentException();
            var sb = new StringBuilder(template);
            for (int i = 0; i < toReplace.Length; i++)
                sb.Replace(toReplace[i], replacements[i]);
            return sb.ToString();
        }

19 View Source File : StringFilters.cs
License : MIT License
Project Creator : ASStoredProcedures

public static string LikeToRegEx(string pattern)
        {
            Context.TraceEvent(100, 0, "Like: Converting Like to RegEx");
            Context.CheckCancelled(); // Check if the user has cancelled 

            StringBuilder sb = new StringBuilder(pattern);
            // the order of the following operations is important or one replacement
            // can end up corrupting a previous replacement.
            sb.Replace(@"\", @"\\"); // needs to be done first before any other backslashes are introduced
            sb.Replace("*", @"\*");  // needs to be done before the '.*' insertion
            sb.Replace(".", @"\.");  // needs to be done before the '.*' insertion
            sb.Replace("%", ".*");
            sb.Replace("$", @"\$");
            sb.Replace("(", @"\(");
            sb.Replace(")", @"\)");
            sb.Replace("|", @"\|");
            sb.Replace("+", @"\+");
            sb.Replace("?", @"\?");
            sb.Replace("^", @"\^");
            // fix up strings where the above replace was too agressive and the
            // ^ was being used as part of a 'not matching' expression.
            sb.Replace(@"[\^", @"[^");
            sb.Replace("[[]", @"\[");
            sb.Replace("_", ".");
            // the above replacement incorrectly converts both _ to . and [_] to [.]
            // the next line converts the incorrect [.] to _
            sb.Replace("[.]", @"_");

            if (!pattern.StartsWith("%")) { sb.Insert(0, @"\A"); }
            if (!pattern.EndsWith("%")) { sb.Append(@"\z"); }
            return sb.ToString();
        }

19 View Source File : TextUtils.cs
License : GNU General Public License v3.0
Project Creator : AtomCrafty

public static string ReplaceSpecialChars(string source) {
			StringBuilder sb = new StringBuilder(source);

			// use ─ for seamless lines
			// supported special characters: ★☆♀♂♪♭♯

			sb.Replace('(', '(');
			sb.Replace(')', ')');
			sb.Replace('『', '"');
			sb.Replace('』', '"');
			sb.Replace("「", "");
			sb.Replace("」", "");
			sb.Replace("、", ", ");
			sb.Replace("。", ". ");
			sb.Replace("…", "...");
			sb.Replace('!', '!');
			sb.Replace('?', '?');
			sb.Replace('~', '~');
			sb.Replace('⁓', '~');
			sb.Replace('–', '—');
			sb.Replace('—', '—');
			sb.Replace('ー', '—');
			sb.Replace('ー', '—');
			sb.Replace('―', '—');
            sb.Replace('─', '—');
            sb.Replace('’', '\'');

			return sb.ToString();
		}

See More Examples