0

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

radren
  • 154
  • 2
  • 14
  • Everything doable is possible in C#. Why do you even ask? How to do it? Depends on the amount of time you want to invest. I would probably start with a simple CSV reader like kbcsv, to read the files into a data structure. Displaying and changing amounts then is a piece of cake (bot you would have to think for yourself) – Christian Sauer Mar 13 '17 at 07:35

3 Answers3

1

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();
Youri Leenman
  • 228
  • 2
  • 8
0

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.

Luci
  • 1,278
  • 9
  • 17
0

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

Community
  • 1
  • 1
Mong Zhu
  • 23,309
  • 10
  • 44
  • 76