C# write multi lines to cs file
I googled and found the solution at MSDN.
// Compose a string that consists of three lines.
string lines = "First line.\r\nSecond line.\r\nThird line.";
// Write the string to a file.
System.IO.StreamWriter file = new System.IO.StreamWriter("c:\\test.txt");
file.WriteLine(lines);
file.Close();
How to extend the lines to complex content which including some natural C# code lines. eg. I want to write the information below to my test.cs file.
Why? I am parsing a XML schema with C# Console Application. And i want to generate the Console Result to a .cs file during the compiler time.
using System;
开发者_运维技巧using System.Collections.Generic;
using System.Text;
namespace CommonDef
{
public class CCODEData
{
public int iCodeId;
public string sCode;
public CODEDType cType;
public int iOccures;
}
[Description("CodeType for XML schema.")]
public enum CODEDType
{
cString = 1,
cInt = 2,
cBoolean = 3,
}
thank you.
If your source code is hardcoded as in your sample, you could use a C# literal string:
string lines =
@"using System;
using System.Collections.Generic;
using System.Text;
namespace CommonDef
..."
Anyway in such cases it is a better idea (more readable and maintainable) to have the whole text contents into a text file as an embedded resource in your assembly, then read it using GetManifestResourceStream.
(I'm assuming you're trying to build up the result programmatically - if you genuinely have hard-coded data, you could use Konamiman's approach; I agree that using an embedded resource file would be better than a huge verbatim string literal.)
In your case I would suggest not trying to build up the whole file into a single string. Instead, use WriteLine
repeatedly:
using (TextWriter writer = File.CreateText("foo.cs"))
{
foreach (string usingDirective in usingDirectives)
{
writer.WriteLine("using {0};", usingDirective);
}
writer.WriteLine();
writer.WriteLine("namespace {0}", targetNamespace);
// etc
}
You may wish to write a helper type to allow simple indentation etc.
If these suggestions don't help, please give more details of your situation.
I know an answer has already been accepted but why not use an XSLT applied to the XML instead? this would mean that you could easily generate c#, vb.net, .net without having to recompile the app.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace FileHandling
{
class Class1
{
static void Main()
{
Console.WriteLine("Enter data");
ConsoleKeyInfo k;
//Console.WriteLine(k.KeyChar + ", " + k.Key + ", " + k.Modifiers );
string str="";
char ch;
while (true)
{
k = Console.ReadKey();
if ((k.Modifiers == ConsoleModifiers.Control) && (k.KeyChar == 23))
{
Console.WriteLine("\b");
break;
}
if (k.Key == ConsoleKey.Enter)
{
Console.WriteLine("");
str += "\n";
}
ch = Convert.ToChar(k.KeyChar);
str += ch.ToString();
}
Console.WriteLine(str);
Console.Read();
}
}
}
精彩评论