radren
radren

Reputation: 153

how to read, write, process txt file like database in c# console

i'm new to c#, i was given an assignment to use txt file as database for c#. example: this is the content of product.txt

product_name;price;stock;
cappucino;3500;12;
vanilla_milk;5000;12;
orange_juice;4500;10;
mineral_water;2000;15;

and i want to use that product.txt to display it on my c# console program

Console.WriteLine("What Coffee would you like to buy? ");
//display the cappucino product name and price from product.txt

also i want to edit the stock from product.txt when product is purchased

is it possible, how to do it?

found it, sorry for my stupid question. i just don't know the keyword, that is streamwriter

Upvotes: 0

Views: 4651

Answers (3)

Youri Leenman
Youri Leenman

Reputation: 248

This is a good way of loading the data

List<Product> allProducts = new List<Product>();

List<string> productlines = File.ReadAllLines("Product.txt").ToList();

//Remove headers
productlines.RemoveAt(0);

foreach(string line in productlines)
{
     string[] parts = line.Split(';');

     Product product = new Product();
     product.Name = parts[0];
     product.Price = Convert.ToInt32(parts[1]);
     product.Quantity = Convert.ToInt32(parts[2]);

     allProducts.Add(product);
}

And for the product class

class Product
{
    public string Name { get; set; }
    public int Price { get; set; }
    public int Quantity { get; set; }

}

To filter the date you could use linq like this

List<Product> filteredProducts = allProduct.Where(x =>x .Name == "Cappuchino").ToList();

Upvotes: 1

Mong Zhu
Mong Zhu

Reputation: 23732

I give you a starting point. You will need

1) a method that loads your database
2) inside that method you can use System.IO.File.ReadAllLines(string path) to read all lines of your txt-database. You can use String.Split(';') to split each line into its parts. You will now have a string array which contains 1 element.

Now if your first line contains the names of the columns you could use either the names to get the index of each column and use this index for each line or you could use names to populate an object of a certain type using reflection. Setting a property by reflection with a string value will tell you how to do it.

If you use the second approach then you can end up with a list of items which is queryable with linq like a database.

Hope it helps

Upvotes: 0

Luci
Luci

Reputation: 1396

If your file is not big you could read it all parse the lines and create a list of objects {name, price, stock}. Do whatever you want and then save the new list into the file.

Upvotes: 0

Related Questions