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


C# StringWriter.ToString方法代码示例

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


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

示例1: GetWellFormedHTML

 public static string GetWellFormedHTML(string html, string xpathNavPath)
 {
     // StreamReader sReader = null;
     StringWriter sw = null;
     SgmlReader reader = null;
     XmlTextWriter writer = null;
     try
     {
         //  if (uri == String.Empty) uri = "http://www.XMLforASP.NET";
         // HttpWebRequest req = (HttpWebRequest)WebRequest.Create(uri);
         //  HttpWebResponse res = (HttpWebResponse)req.GetResponse();
         //  sReader = new StreamReader(res.GetResponseStream());
         reader = new SgmlReader();
         reader.DocType = "HTML";
         reader.InputStream = new StringReader(html);
         sw = new StringWriter();
         writer = new XmlTextWriter(sw);
         writer.Formatting = Formatting.Indented;
         //writer.WriteStartElement("Test");
         while (reader.Read())
         {
             if (reader.NodeType != XmlNodeType.Whitespace)
             {
                 writer.WriteNode(reader, true);
             }
         }
         //writer.WriteEndElement();
         if (xpathNavPath == null)
         {
             string sr = sw.ToString();
             sr = sr.Replace("\r", "\n");
             sr = sr.Replace("\n\n", "\n");
             return sr;
         }
         else
         { //Filter out nodes from HTML
             StringBuilder sb = new StringBuilder();
             XPathDocument doc = new XPathDocument(new StringReader(sw.ToString()));
             XPathNavigator nav = doc.CreateNavigator();
             XPathNodeIterator nodes = nav.Select(xpathNavPath);
             while (nodes.MoveNext())
             {
                 sb.Append(nodes.Current.Value + "\n");
             }
             string sr = sb.ToString();
             sr = sr.Replace("\r", "\n");
             sr = sr.Replace("\n\n", "\n");
             return sr;
         }
     }
     catch (Exception exp)
     {
         writer.Close();
         reader.Close();
         sw.Close();
         // sReader.Close();
         return exp.Message;
     }
 }
开发者ID:drzo,项目名称:opensim4opencog,代码行数:59,代码来源:HttpUtil.cs

示例2: Index

        public ActionResult Index([Diagnostics.NotNull] string route)
        {
            var actionResult = this.AuthenticateUser();
            if (actionResult != null)
            {
                return actionResult;
            }

            var output = new StringWriter();
            Console.SetOut(output);

            var projectDirectory = WebUtil.GetQueryString("pd");
            var toolsDirectory = WebUtil.GetQueryString("td");
            var binDirectory = FileUtil.MapPath("/bin");

            var app = new Startup().WithToolsDirectory(toolsDirectory).WithProjectDirectory(projectDirectory).WithExtensionsDirectory(binDirectory).Start();
            if (app == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.InternalServerError, output.ToString());
            }

            var instance = ((CompositionContainer)app.CompositionService).GetExportedValue<IWebApi>(route);
            if (instance == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest, "Route not found: " + route);
            }

            var result = instance.Execute(app);

            return result ?? Content(output.ToString(), "text/plain");
        }
开发者ID:pveller,项目名称:Sitecore.Pathfinder,代码行数:31,代码来源:PathfinderWebApiController.cs

示例3: TestWrite

        public void TestWrite() {
                StringWriter writer = new StringWriter();

                Assert.AreEqual (String.Empty, writer.ToString());
                
                writer.Write( 'A' );
                Assert.AreEqual ("A", writer.ToString());

                writer.Write( " foo" );
                Assert.AreEqual ("A foo", writer.ToString());

                
                char[] testBuffer = "Test String".ToCharArray();

                writer.Write( testBuffer, 0, 4 );
                Assert.AreEqual ("A fooTest", writer.ToString());

                writer.Write( testBuffer, 5, 6 );
                Assert.AreEqual ("A fooTestString", writer.ToString());

		writer = new StringWriter ();
                writer.Write(null as string);
                Assert.AreEqual ("", writer.ToString());

        }
开发者ID:KonajuGames,项目名称:SharpLang,代码行数:25,代码来源:StringWriterTest.cs

示例4: TestCultureInfoConstructor

        public void TestCultureInfoConstructor() {

		StringWriter writer = new StringWriter(CultureInfo.InvariantCulture);
		Assert.IsNotNull (writer.GetStringBuilder());
		
		Assert.AreEqual (String.Empty, writer.ToString());
		
		writer.Write( 'A' );
		Assert.AreEqual ("A", writer.ToString());
		
		writer.Write( " foo" );
		Assert.AreEqual ("A foo", writer.ToString());
		
		
		char[] testBuffer = "Test String".ToCharArray();
		
		writer.Write( testBuffer, 0, 4 );
		Assert.AreEqual ("A fooTest", writer.ToString());
		
		writer.Write( testBuffer, 5, 6 );
		Assert.AreEqual ("A fooTestString", writer.ToString());
		
		writer = new StringWriter(CultureInfo.InvariantCulture);
		writer.Write(null as string);
		Assert.AreEqual ("", writer.ToString());
        }
开发者ID:KonajuGames,项目名称:SharpLang,代码行数:26,代码来源:StringWriterTest.cs

示例5: StrippedHtmlIsSameAsInput

        public void StrippedHtmlIsSameAsInput()
        {
            var input = SampleFile.Load("csharp-sample.txt");
            var tokens = new CSharpLexer()
                .GetTokens(input)
                .ToArray();

            var subject = new HtmlFormatter(new HtmlFormatterOptions()
            {
                NoWrap = true
            });

            var htmlOut = new StringWriter();
            subject.Format(tokens, htmlOut);

            File.WriteAllText("output.html", htmlOut.ToString());

            var txtOut = new StringWriter();
            new NullFormatter().Format(tokens, txtOut);

            var strippedHtml = Regex.Replace(htmlOut.ToString(),
                @"<.*?>", "")
                .Trim();
            var escapedText = HtmlFormatter.EscapeHtml(txtOut.ToString()).Trim();

            Check.That(strippedHtml).IsEqualTo(escapedText);
        }
开发者ID:akatakritos,项目名称:PygmentSharp,代码行数:27,代码来源:HtmlFormatterTests.cs

示例6: add_dividers_and_jagged_columns

        public void add_dividers_and_jagged_columns()
        {
            var report = new TextReport();
            report.AddDivider('=');
            report.StartColumns(3);
            report.AddText("This is the header");
            report.AddDivider('=');

            report.AddColumnData("a1***", "b1", "c1");
            report.AddColumnData("a2", "b2***", "c2");
            report.AddColumnData("a3", "b3", "c3***");
            report.AddDivider('=');

            var writer = new StringWriter();

            report.Write(writer);

            Debug.WriteLine(writer.ToString());

            writer.ToString().ShouldEqualWithLineEndings(@"
            =========================
            This is the header
            =========================
            a1***     b1        c1
            a2        b2***     c2
            a3        b3        c3***
            =========================
            ");
        }
开发者ID:rasupit,项目名称:fubucore,代码行数:29,代码来源:TextReportTester.cs

示例7: SendBuffer

		protected override void SendBuffer(LoggingEvent[] events)
		{
			if (crashReportSender == null || events == null || events.Length == 0)
				return;

			try
			{
				using (var writer = new StringWriter(CultureInfo.InvariantCulture))
				{
					for (int index = 0; index < events.Length; ++index)
						RenderLoggingEvent(writer, events[index]);

					LoggingEvent le = events[events.Length - 1];

					string crashMessage = le.ExceptionObject == null
										 ? string.Format("MSG - {0}", le.MessageObject)
										 : string.Format("EXC - {0} : {1}", le.ExceptionObject.GetType().Name, le.ExceptionObject.Message);

					if (SendAsync)
					{
						Action<string, string> action = crashReportSender.Send;
						action.BeginInvoke(writer.ToString(), crashMessage, Sent, action);
					}
					else
					{
						crashReportSender.Send(writer.ToString(), crashMessage);
					}
				}
			}
			catch (Exception ex)
			{
				ErrorHandler.Error("Error occurred while sending crash report to the web.", ex);
			}
		}
开发者ID:itzing,项目名称:Detrack-.NET-API,代码行数:34,代码来源:CrashLogAppender.cs

示例8: Specify

        public override void Specify()
        {
            var trace = new StringWriter();

            when("the user types in input which is rejected by NDesk.Options", delegate
            {
                var lastError = arrange(() => ConsoleCommandDispatcher.DispatchCommand(
                    new ConsoleCommand[] { new SomeCommandWithAParameter() }, 
                    new[] { "some", "/a" }, 
                    trace));
                
                then("the error output gives the error message and typical help", delegate
                {
                    expect(() => lastError != 0);
                    
                    expect(() => trace.ToString().Contains("Missing required value for option '/a'"));
                    expect(() => trace.ToString().Contains(TextWithinExpectedUsageHelp));

                    expect(() => !trace.ToString().ToLower().Contains("ndesk.options"));
                    expect(() => !trace.ToString().ToLower().Contains("exception"));
                });
            });

            when("a command causes other unexpected errors", delegate
            {
                then("the exception passes through", delegate
                {
                    Assert.Throws<InvalidAsynchronousStateException>(() => ConsoleCommandDispatcher.DispatchCommand(
                        new ConsoleCommand[] { new SomeCommandThrowingAnException(), },
                        new string[0],
                        trace));
                });
            });
        }
开发者ID:secomba,项目名称:ManyConsole,代码行数:34,代码来源:Show_useful_error_information.cs

示例9: Append

 protected override void Append(log4net.Core.LoggingEvent loggingEvent)
 {
     using (StringWriter sw = new StringWriter(CultureInfo.InvariantCulture))
     {
         Layout.Format(sw, loggingEvent);
         //The textbox may not be ready at this point, so cache the appended
         //entries into a temp buffer until a textbox is ready. When it is
         //write the contents of the buffer first before writing the most
         //recent event
         if (_TextBox != null && !_TextBox.IsDisposed)
         {
             string content = sw.ToString();
             string level = loggingEvent.Level.Name;
             if (_TextBox.InvokeRequired)
             {
                 _TextBox.BeginInvoke(new WriteContentHandler(this.WriteContent), content, level);
             }
             else
             {
                 WriteContent(content, level);
             }
         }
         else if (_buffer != null)
         {
             _buffer.Append(sw.ToString());
         }
     }
 }
开发者ID:stophun,项目名称:fdotoolbox,代码行数:28,代码来源:TextBoxAppender.cs

示例10: CSharpVisitorSpecTest

        public void CSharpVisitorSpecTest(string fullName, string haml, string html, string format, SpecLocal[] locals)
        {
            var output = new StringWriter();
            var parser = new Core.Parser.Parser();
            var document = parser.Parse(haml);
            var visitor = new DebugCompiler(document, format);

            output.WriteLine("Name: " + fullName);
            foreach (var local in locals)
            {
                output.WriteLine("Var:  " + local.Name + "=" + local.Value);
                visitor.Locals.Add(local.Name, local.Value);
            }
            output.WriteLine("Form: " + format);
            output.WriteLine("Haml: " + haml);
            output.WriteLine("Exp:  " + html.Replace(Environment.NewLine, @"\n"));

            try
            {
                var writer = visitor.Run();

                output.WriteLine("Out:  " + writer.ToString().Replace(Environment.NewLine, @"\n"));
                output.Flush();
                Assert.True(writer.ToString().Equals(html), output.ToString());

                Debug.Write(output);
                Debug.WriteLine("------------------------");
            }
            catch (Exception exception)
            {
                throw new Exception(output.ToString(), exception);
            }
        }
开发者ID:richiejp,项目名称:NHaml,代码行数:33,代码来源:HamlSpecTests.cs

示例11: doit

        public virtual void doit()
        {
            /*
            * make a dvsl
            */
            NVelocity.Dvsl.Dvsl dvsl = new NVelocity.Dvsl.Dvsl();

            /*
            *  register the stylesheet
            */
            dvsl.SetStylesheet(new StringReader(dvslstyle));

            /*
            *  render the document as a Reader
            */
            StringWriter sw = new StringWriter();
            dvsl.Transform(new StringReader(input), sw);

            if (!sw.ToString().Equals("Hello from element! Foo"))
            Assertion.Fail("Result of first test is wrong : " + sw.ToString());

            /*
            * now test if we can pass it a Document
            */
            XmlDocument document = new XmlDocument();
            document.Load(new StringReader(input));

            sw = new StringWriter();
            dvsl.Transform(document, sw);

            if (!sw.ToString().Equals("Hello from element! Foo"))
            Assertion.Fail("Result of second test is wrong : " + sw.ToString());
        }
开发者ID:DF-thangld,项目名称:web_game,代码行数:33,代码来源:TransformTest.cs

示例12: BuildSql

		public override SqlStatementKind BuildSql(StringBuilder b, SqlQueryContext context)
		{
			SqlStatementKind kind = Target.BuildSql(b, context);
			if (kind == SqlStatementKind.SelectOrderBy)
				WrapSqlIntoNestedStatement(b, context);
			
			b.Append(" ORDER BY ");
			
			for (int i = 0; i < arguments.Count; i++) {
				StringWriter w = new StringWriter();
				ExpressionSqlWriter writer = new ExpressionSqlWriter(w, context, arguments[i].Argument.Parameters[0]);
				writer.Write(arguments[i].Argument.Body);
				
				if (i == 0)
					b.Append(w.ToString());
				else
					b.Append(", " + w.ToString());
				
				if (arguments[i].Descending)
					b.Append(" DESC");
				else
					b.Append(" ASC");
			}
			
			return SqlStatementKind.SelectOrderBy;
		}
开发者ID:Paccc,项目名称:SharpDevelop,代码行数:26,代码来源:Sort.cs

示例13: CompareAssemblyAgainstCSharp

		private static void CompareAssemblyAgainstCSharp(string expectedCSharpCode, string asmFilePath)
		{
			var module = Utils.OpenModule(asmFilePath);
			try
			{
				try { module.LoadPdb(); } catch { }
				AstBuilder decompiler = AstBuilder.CreateAstBuilderTestContext(module);
				decompiler.AddAssembly(module, false, true, true);
				new Helpers.RemoveCompilerAttribute().Run(decompiler.SyntaxTree);
				StringWriter output = new StringWriter();

				// the F# assembly contains a namespace `<StartupCode$tmp6D55>` where the part after tmp is randomly generated.
				// remove this from the ast to simplify the diff
				var startupCodeNode = decompiler.SyntaxTree.Children.OfType<NamespaceDeclaration>().SingleOrDefault(d => d.Name.StartsWith("<StartupCode$", StringComparison.Ordinal));
				if (startupCodeNode != null)
					startupCodeNode.Remove();

				decompiler.GenerateCode(new PlainTextOutput(output));
				var fullCSharpCode = output.ToString();

				CodeAssert.AreEqual(expectedCSharpCode, output.ToString());
			}
			finally
			{
				File.Delete(asmFilePath);
				File.Delete(Path.ChangeExtension(asmFilePath, ".pdb"));
			}
		}
开发者ID:levisre,项目名称:dnSpy,代码行数:28,代码来源:TestHelpers.cs

示例14: One_failed_test_should_generate_test_suite_result_as_failure

        public void One_failed_test_should_generate_test_suite_result_as_failure()
        {
            var writer = new StringWriter();
            var formatter = new NUnitTestResultsFormatter(writer);
            formatter.Format(new StatLightResult("test", DateTime.ParseExact("2011-04-09", "yyyy-MM-dd", null), new[] {
                new StatLightTestResult("test1", true, false, false, "", "", TimeSpan.Zero),
                new StatLightTestResult("test2", false, true, false, "", "", TimeSpan.Zero),
                new StatLightTestResult("test3", false, false, true, "test-failure", "test-stack", TimeSpan.Zero)
            }));

            Console.WriteLine(writer.ToString());
            Assert.AreEqual(@"<?xml version=""1.0"" encoding=""utf-16""?>
            <test-results name=""test"" total=""3"" not-run=""1"" failures=""1"" date=""2011-04-09"" time=""00:00:00"">
              <test-suite type=""TestFixture"" name=""test"" executed=""True"" result=""Failure"" success=""False"">
            <results>
              <test-case name=""test1"" executed=""True"" time=""00:00:00.0000"" result=""Success"" success=""True"" />
              <test-case name=""test2"" executed=""False"" time=""00:00:00.0000"" result=""Ignored"" />
              <test-case name=""test3"" executed=""True"" time=""00:00:00.0000"" result=""Failure"" success=""False"">
            <failure>
              <message>test-failure</message>
              <stack-trace><![CDATA[test-stack]]></stack-trace>
            </failure>
              </test-case>
            </results>
              </test-suite>
            </test-results>", writer.ToString());
        }
开发者ID:andywhitfield,项目名称:StatLightToNUnitReportGenerator,代码行数:27,代码来源:NUnitTestResultsFormatterTest.cs

示例15: Main

 static void Main(string[] args)
 {
     StringBuilder sb = new StringBuilder();
     StringWriter sw = new StringWriter(sb);
     using (JsonWriter writer = new JsonTextWriter(sw))
     {
         writer.Formatting = Newtonsoft.Json.Formatting.Indented;
         writer.WriteStartObject();
         writer.WritePropertyName("CPU");
         writer.WriteValue("Intel");
         writer.WritePropertyName("PSU");
         writer.WriteValue("500W");
         writer.WritePropertyName("Drives");
         writer.WriteStartArray();
         writer.WriteValue("DVD read/writer");
         writer.WriteComment("(broken)");
         writer.WriteValue("500 gigabyte hard drive");
         writer.WriteValue("200 gigabype hard drive");
         writer.WriteEnd();
         writer.WriteEndObject();
     }
     File.WriteAllText(Environment.CurrentDirectory + "/rhcdata.json", sw.ToString());
     Console.WriteLine(sw.ToString());
     Console.ReadLine();
 }
开发者ID:MaurodeLyon,项目名称:Huiswerk-CSharp,代码行数:25,代码来源:Program.cs


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