Writing to a comma delimited text file
I am having a difficult time with finding how to write to a comma delimited text file. I am creating a very basic address form for myself. I would like w开发者_Go百科hen I click button1 that it creates a text file then writes the data from textbox1, textbox2, textbox3, and maskedtextbox1 to that file seperated by commas.
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void close_Click(object sender, EventArgs e)
{
Close();
}
}
}
Creating csv files is very easy. Try the following:
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 }));
}
Alternatively, if you don't like the string.Format method, you could do the following:
using (StreamWriter sw = new StreamWriter("C:\\text.txt", true))
{
sw.WriteLine(s1 + "," + s2 + "," + s3 + "," + s4}));
}
You will need to use two classes: FileStream and StreamWriter. And maybe this documentation. But as I suspect that this is a homework assignment, I'm leery to provide any more assistance. You should be able to figure it out easily enough.
精彩评论