开发者

CreateText method extension help

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 Sy开发者_JS百科stem;
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();
        }
    }
}


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?


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


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();        
}    
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜