Czajka Czajka - 1 year ago 74
C# Question

C# Check in CSV and get all data from row to variable

I have CSV file like:

Head1; Head2; Head3; Head4;
test1; word1; word2; word3;
test2; word1, word2; word3;
test3; word1; word2; word3;


And i search for example "test2" from textBox1.Text

Private void button1_Click(object sender, RoutedEventArgs e)
{
string NS = textBox1.Text;
bool found = File
.ReadLines(@"test.csv")
.Any(line => line.Contains(NS));

if (found)
MessageBox.Show("Test found!");


but, I have no idea, how to make single variables from row, where found "test2".
Something like:
First variable: head2 = word1
Second variable: head3 = word2
etc.

Answer Source

You can try this.

               string NS = textBox1.Text;

               var foundRecord =  File
                  .ReadLines(@"test.csv")
                  .Where(line => line.Contains(NS)).FirstOrDefault();

                if (foundRecord != null)
                {
                    var cols = foundRecord.Split(';'); //split by (;)
                    var firstVar = cols[0]; //capture column in variable
                    var secondVar = cols[1];
                    var thirdVar = cols[2];
                }
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download