R.B R.B - 1 month ago 9
C# Question

Read from textfile and split each line into different strings

i have to read from a textfile which contains the following formatting

PRODUCTID PRODUCTNAME CUSTOMERID CUSTOMERNAME AMOUNT.


The textfile contains 11 line and for each one of them i must store each eg. productid into one string, and productname into one string.

I have tried like this which only stores the length of each line..

List<string> list = new List<string>();
using (var reader = new StreamReader(@"Budget.txt"))
{

string line;
while ((line = reader.ReadLine()) != null)
{
list.Add(line);
}
}


I want to store it temporarly like this:

string productID = line.productid;


or something so i can use them

Answer

Create a class that rapresent your file line, like this:

public class Procuct {
    public string ProductId {get;set;}
    public string ProductName {get;set;}
    public string CustomerId {get;set;}
    public string CustomerName {get;set;}
    public string Amount{get;set;}
}

Then create a list of product to store them:

    List<Procuct> list = new List<Procuct>();
    using (var reader = new StreamReader(@"Budget.txt"))
    {

        string line;
        while ((line = reader.ReadLine()) != null)
        {               
            var temp = line.Split(" ");
            list.Add(new Product{
                ProductId = temp[0],
                ProductName = temp[1],
                CustomerId = temp[2],
                CustomerName = temp[3],
                Amount = temp[4]
            });
        }
    }  

Once are stored you can use LINQ to get the information that you want.