CreateText方法扩展帮助

时间:2009-12-24 03:36:27

标签: c# .net

美好的一天。

我找到了下面的例子,

我需要从另一个Sub()函数中添加更多文本。 但我不知道该怎么做。 你能给我一些指导吗? 感谢。

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

3 个答案:

答案 0 :(得分:1)

如果您的函数返回一个字符串(或其他可写类型),您可以执行以下操作:sw.WriteLine(theSubINeedToCall());

如果需要处理返回的对象,可以创建一个包装器调用并将streamWriter传递给它,然后处理它,即:

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

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

答案 1 :(得分:1)

如果另一个函数返回你想要写的文本,那就写下来:

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

如果您想要将文本附加到现有文件而不是创建新文件,请使用File.AppendText而不是File.CreateText。

如果那不是你想要做的,你能澄清一下这个问题吗?

答案 2 :(得分:1)

在您的班级内的主要内容之后添加此内容

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

然后在Main中调用它

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