简体   繁体   English

写入以逗号分隔的文本文件

[英]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 when 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. 我想当我单击button1时,它会创建一个文本文件,然后将textbox1,textbox2,textbox3和maskedtextbox1中的数据写入到以逗号分隔的文件中。

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


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

 }

Creating csv files is very easy. 创建csv文件非常容易。 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: 或者,如果您不喜欢string.Format方法,则可以执行以下操作:

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. 您将需要使用两个类:FileStream和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. 您应该能够很容易地弄清楚它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM