2010-11-09 77 views
0

我在查找如何寫入以逗號分隔的文本文件時遇到困難。我正在爲自己創建一個非常基本的地址表單。當我點擊button1時,它會創建一個文本文件,然後將數據從textbox1,textbox2,textbox3和maskedtextbox1寫入到由逗號分隔的文件中。寫入以逗號分隔的文本文件

public partial class Form1 : Form 
{ 
    public Form1() 
    { 
     InitializeComponent(); 
    } 


    private void close_Click(object sender, EventArgs e) 
    { 
     Close(); 
    } 
} 

} 
+0

這裏沒有問題。你的問題是什麼? – abelenky 2010-11-09 21:07:22

+0

問題在頂部。我想知道如何編寫輸入到文本文件的信息。 – user770022 2010-11-09 21:09:57

+0

問題以問號(?)結尾。除了想要的東西,你沒有,你有什麼困難?你有什麼嘗試?你不明白什麼? – abelenky 2010-11-09 21:14:55

回答

0

您將需要使用兩個類:FileStream和StreamWriter。也許this documentation。但是因爲我懷疑這是一項家庭作業,所以我很抱歉提供更多的幫助。你應該能夠很容易地弄清楚它。

+0

不是作業,但是謝謝 – user770022 2010-11-09 20:41:25

5

創建csv文件非常簡單。請嘗試以下操作:

string s1 = TextBox1.Text; 
string s2 = TextBox2.Text; 
string s3 = TextBox3.Text; 
string s4 = maskedtextbox1.Text; 

using (StreamWriter sw = new StreamWriter("C:\\text.txt", true)) // True to append data to the file; false to overwrite the file 
{ 
    sw.WriteLine(string.Format("[0],[1],[2],[3]", new object[] { s1, s2, s3, s4 })); 
} 

另外,如果你不喜歡String.Format方法,你可以做到以下幾點:

using (StreamWriter sw = new StreamWriter("C:\\text.txt", true)) 
{ 
    sw.WriteLine(s1 + "," + s2 + "," + s3 + "," + s4})); 
} 
+1

或者:'sw.WriteLine(string.Join(「,」,new object [] {s1,s2,s3,s4}));' – BeemerGuy 2010-11-09 21:45:45

+0

您在代碼中的評論不正確。 StreamWriter的第二個參數是可以追加的,false是可以覆蓋的。 – JBrooks 2013-06-05 18:23:48

+0

@JBrooks - 感謝您的評論。有人終於在2.5年後發現:) – Lane 2013-08-04 02:04:43

相關問題