2009-12-24 79 views
0

美好的一天。CreateText方法擴展幫助

我發現下面的例子中,

我需要從另一個小組()函數追加一些更多的文本。 但我不知道如何。 你能給我一些指導嗎? 謝謝。

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

如果其他函數返回你想要寫的文字,那麼就寫:

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

如果您想將文本附加到現有文件而不是創建新文件,請使用File.AppendText而不是File.CreateText。

如果這不是你想要做的,你能澄清這個問題嗎?

+0

嗨itowlson,我想創建一個新的。在建築時間內添加來自不同子解析函數的其他內容。然後我可以爲我的主要項目生成一個foo.cs文件。謝謝。 – 2009-12-24 03:52:26

+0

File.AppendText工程。謝謝。 – 2009-12-24 05:49:17

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

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

內主後添加此然後調用它的主這樣

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