简体   繁体   English

C#从逗号分隔的文本文件读取到Windows窗体

[英]C# Reading from Comma Separated Text File to Windows Form

I've created a windows form that takes user input and writes it to a text file in a comma separated manner and appends each new line. 我创建了一个Windows窗体,该窗体接受用户输入并将其以逗号分隔的方式写入文本文件,并追加每行。 I want to be able to read all the data from that file and display it to the user on another windows form in either a rich text box or label. 我希望能够从该文件中读取所有数据,并通过富文本框或标签在另一个Windows窗体上将其显示给用户。

The code below is what I have to read in the data to a specific location on my machine. 下面的代码是我必须将数据读取到计算机上特定位置的内容。 I'm not sure if I first need to read the data into an array and then send that to a label or text box. 我不确定是否首先需要将数据读入数组,然后将其发送到标签或文本框。

using (StreamWriter InputFile = File.AppendText(@"C:\Users\person\Desktop\C#\New Text Document.txt"))
        {
            InputFile.WriteLine(textBox1.Text + "," + textBox2.Text + "," + textBox3.Text + "," + textBox4.Text);
            MessageBox.Show("Data Saved!");

I know there are many other posts like this, but I can't seem to get the answer I'm looking for 我知道还有很多其他这样的帖子,但是我似乎无法获得我要找的答案

yes you have to read all lines in an array and using a code like the following 是的,您必须读取数组中的所有行并使用类似以下的代码

var lines =File.ReadAllLines(@"C:\Users\person\Desktop\C#\New Text Document.txt");
            foreach (var line in lines)
            {
                var col = line.Split(',');
                textBox1.Text = col[0]; 
                   textBox2.Text = col[1];
                textBox3.Text = col[2];
                textBox4.Text = col[3]; 
            } 

No, you could use File.ReadLines , which returns an IEnumerable<string> . 不,您可以使用File.ReadLines ,它返回IEnumerable<string>

int i = 1;
foreach (string line in File.ReadLines(path)) {
    string[] columns = line.Split(',');
    for (int c = 0; c < columns.Length; c++) {
        ((TextBox)Controls["textBox" + i++]).Text = columns[c];
    }
}

I assume that you have textboxes names textBox1 to textBox4 for the first line, textBox5 to textBox8 for the second line, and so on. 我假设您有第一行的文本框名称为textBox1textBox4 ,第二行的文本框名称为textBox5textBox8 ,依此类推。 But it would probably be better to use a grid. 但是使用网格可能会更好。

Consider also using the TextFieldParser in the namespace Microsoft.VisualBasic.FileIO . 还考虑在名称空间Microsoft.VisualBasic.FileIO使用TextFieldParser It does all the CSV processing for you. 它为您完成所有CSV处理。 You will have to add a reference to the Microsoft.VisualBasic.dll . 您将必须添加对Microsoft.VisualBasic.dll的引用。

Note: the stuff in Microsoft.VisualBasic.dll is just a .NET library like any other and works as well in C# as in VB. 注意:Microsoft.VisualBasic.dll中的内容只是一个.NET库,与其他任何库一样,并且在C#中的效果与在VB中一样。

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

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