tags:

views:

36

answers:

3

Hello.

Good day.

I found the example below,

I need to append some more text from another Sub() function. But i don't know how to. Could you give me some guide? THANKS.

using System;
using System.IO;
public class TextToFile 
{
    private const string FILE_NAME = "MyFile.txt";
    public static void Main(String[] args) 
    {
        if (File.Exists(FILE_NAME)) 
        {
            Console.WriteLine("{0} already exists.", FILE_NAME);
            return;
        }
        using (StreamWriter sw = File.CreateText(FILE_NAME))
        {
            sw.WriteLine ("This is my file.");
            sw.WriteLine ("I can write ints {0} or floats {1}, and so on.", 
                1, 4.2);
            sw.Close();
        }
    }
}
+1  A: 

If your function returns a string (or other writable type) you can simply do: sw.WriteLine(theSubINeedToCall());

If you need to process the returned object, you can create a wrapper call and pass the streamWriter to it and then process it i.e:

public void writeOutCustomObject(StreamWriter writer) {
   SomeObject theObject = getSomeCustomObject();

   writer.WriteLine("ID: " + theObject.ID);
   writer.WriteLine("Description: " + theObject.Description);
   //.... etc ....
}
GrayWizardx
+1  A: 

If the other function returns the text you want to write, then just write it:

string text = SomeOtherFunction();
sw.Write(text);  // or WriteLine to append a newline as well

If you're wanting to append text to an existing file rather than creating a new one, use File.AppendText instead of File.CreateText.

If that's not what you're trying to do, can you clarify the question?

itowlson
Hi itowlson, i want to create a new one. Add some other content from differents sub parse functions during the buiding time. Then i could generate a foo.cs file for my mainly project. thanks.
Nano HE
<code> File.AppendText </code> works. thank you.
Nano HE
+1  A: 

add this after Main inside your class

public static void SubFunction(StreamWriter sw)
{
    sw.WriteLine("This is more stuff I want to add to the file");
    // etc...
}

And then call it in Main like this

using (StreamWriter sw = File.CreateText(FILE_NAME))        
{            
    sw.WriteLine ("This is my file.");            
    sw.WriteLine ("I can write ints {0} or floats {1}, and so on.",               1,4.2);
    MySubFunction(sw); // <-- this is the call
    sw.Close();        
}
John Knoeller