tags:

views:

330

answers:

3

Hello.

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.

+4  A: 

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.

Konamiman
Some lines like using System, etc is hardcoded.Some other lines like the content from the XSD file would be parsed by System.Xml.Schema automatically. Thanks.
Nano HE
+3  A: 

(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.

Jon Skeet
Thanks Jon. It's a good solution for me special for the part of XSD parser code. I will update the my code from Console.WriteLine() to Writer.WriteLine().
Nano HE
+1  A: 

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.

Mauro
I never learned XSLT before. :-) When i plan my project. i just think i should parse the XSD file with C# or Perl. Thanks for your information.
Nano HE