Hello,

in my program i want to read data from text file and display the data as keyvalue pair using console application.
i am using below code to read the data

{
                         string[] lines = System.IO.File.ReadAllLines(@"C:\Users\ramy\desktop\grocery billing.txt");
                        System.Console.WriteLine("Contents of grocery billing.txt :");
                        foreach (string line in lines)
                        {
                            Console.WriteLine(line);
                           // Console.WriteLine(",", line);
                            
                        }
                        Console.Write("press enter key to exit");
                        Console.Read();
                        break;
                        
                    }

how to display the data as keyvalue pairs? any idea how to proceed

Thanks in advance

As an idea,

Split the variable "line"(for loop var) with the character that separates key and value.

You can play with String.Format option to print the values.

Give a try and update us.

good luck.

p.s: always use code-tags while posting the source code.

Hello,

in my program i want to read data from text file and display the data as keyvalue pair using console application.
i am using below code to read the data

                {
                     string[] lines = System.IO.File.ReadAllLines(@"C:\Users\ramy\desktop\grocery billing.txt");
                    System.Console.WriteLine("Contents of grocery billing.txt :");
                    foreach (string line in lines)
                    {
                        Console.WriteLine(line);
                       // Console.WriteLine(",", line);

                    }
                    Console.Write("press enter key to exit");
                    Console.Read();
                    break;

                }

how to display the data as keyvalue pairs? any idea how to proceed

Thanks in advance

It really depends on the layout of your input file and how you want to parse it.
Let's say it is a numbered list, tab delimited.

1	candy
2	beer
3	peanut butter
4	crackers

... you can use the code to put the data into a Dictionary (collection of key/value pairs with unique key)

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;

namespace DW_393339
{
   public class CDW_393339
   {
      public static void Main(String[] args)
      {
         Dictionary<string, string> map = File.ReadAllLines("../../TextFile1.txt")
            .ToList().Select(s => s.Split('\t')).ToDictionary(k => k[0], v => v[1]);
      }
   }
}

If the items are not unique, you can convert them to the ILookup

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;

namespace DW_393339
{
   public class CDW_393339
   {
      public static void Main(String[] args)
      {
         ILookup<string, string[]> lkup = File.ReadAllLines("../../TextFile1.txt")
            .ToList().Select(s => s.Split('\t')).ToLookup(k => k[0]);
      }
   }
}

hello,

namespace grocery_billing
{
    class WriteFile
    {
        public void WriteData(String Item, DateTime date, float cost)
        {
            FileStream fs = new FileStream(Environment.GetFolderPath(Environment.SpecialFolder.Desktop) + "\\" + "grocery billing.txt", FileMode.OpenOrCreate, FileAccess.Write);
            StreamWriter sw = new StreamWriter(fs);
            sw.BaseStream.Seek(0, SeekOrigin.End);
            sw.WriteLine(Item);
            sw.WriteLine(date);
            sw.WriteLine(cost);
            sw.Flush();
            sw.Close();
        }
        
                                           
        public static void Main()
        {

           
            WriteFile wf = new WriteFile();
            int choice, Key;
            float Price,TotalCost =0;
            string ItemDescription;
            DateTime Date;
            File.Create(Environment.GetFolderPath(Environment.SpecialFolder.Desktop) + "grocery billing.txt");
            Console.WriteLine("Press 1 to read data from file");
            Console.WriteLine("press 2 to enter data");
            Console.WriteLine("press 3 to exit");
            choice = int.Parse(Console.ReadLine());
            
            switch (choice)
            {
                case 1:
                    {
                        string[] lines = System.IO.File.ReadAllLines(@"C:\Users\ramy\desktop\grocery billing.txt");
                        
                        
                        foreach (string line in lines)
                        {
                            Console.WriteLine(line);
                            
                        }
                        Console.Write("press enter key to exit");
                        Console.Read();
                                               
                        break;
                        
                    }
                       
                                 
                case 2:
                    {
                        do
                        {
                            Console.Write("item:");
                            ItemDescription = Console.ReadLine();
                            Console.Write("Date of purchse:");
                            Date = DateTime.Parse(Console.ReadLine());
                            Console.Write("cost:");
                            Price = float.Parse(Console.ReadLine());
                            TotalCost += Price;
                            Console.Write("TotalCost:");
                            Console.WriteLine(TotalCost);
                                                                                
                            wf.WriteData(ItemDescription, Date, Price);
                            Console.WriteLine("If you want to enter more data press 2 ");
                            Key = int.Parse(Console.ReadLine());
                        
                        } while (Key== 2);

                        break;
                    }


                          /*  StreamWriter fileWriter = new StreamWriter("grocery billing.txt");
                            fileWriter.Close();
                            FileStream fs = new FileStream(@"C:\Users\ramya\desktop\grocery billing.txt", FileMode.OpenOrCreate, FileAccess.Write);
                            StreamWriter sw = new StreamWriter(fs);
                            sw.BaseStream.Seek(0, SeekOrigin.End);
                            sw.WriteLine("the item:" + ItemDescription);
                            sw.WriteLine("date of purchase:" + Date);
                            sw.WriteLine("the amount:" + Price);
                            sw.Flush();
                            sw.Close();*/
                            

                        
                case 3:
                    {
                     
                        break;
                        
                    }
                
             }
        }
    }

i am writing the output of a program to text file.
for example my text file on the desktop will be as shown below
item: walmart
date of purchase: 12/12/2011
price:23
totalcost:23
so here ,after reading from the file i want to display <walmart> <23>(i.e., only item description and cost)
while i am trying with the code provided by u its giving an out of range exception error.
any suggestions how to proceed

Thanks in advance

It really depends on the layout of your input file and how you want to parse it.
Let's say it is a numbered list, tab delimited.

1	candy
2	beer
3	peanut butter
4	crackers

... you can use the code to put the data into a Dictionary (collection of key/value pairs with unique key)

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;

namespace DW_393339
{
   public class CDW_393339
   {
      public static void Main(String[] args)
      {
         Dictionary<string, string> map = File.ReadAllLines("../../TextFile1.txt")
            .ToList().Select(s => s.Split('\t')).ToDictionary(k => k[0], v => v[1]);
      }
   }
}

If the items are not unique, you can convert them to the ILookup

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;

namespace DW_393339
{
   public class CDW_393339
   {
      public static void Main(String[] args)
      {
         ILookup<string, string[]> lkup = File.ReadAllLines("../../TextFile1.txt")
            .ToList().Select(s => s.Split('\t')).ToLookup(k => k[0]);
      }
   }
}

Yes, the code I showed you is expecting the data to be arranged in a horizontal fashion.
Your description is both horizontal and vertical for one item, so something different must be done.

Will there only be one item on the receipt in the file?
If so, the folling example will work:

using System;
using System.Collections.Generic;
using System.IO;

namespace DW_393339
{
   class Program
   {
      /// <summary>
      /// This example reads ONE item from a receipt file.
      /// </summary>
      /// <param name="strFileName">full path to receipt file</param>
      /// <returns>KeyValuePair of one item (or empty kvp)</returns>
      private static KeyValuePair<string, double> GetOneItemFromReceipt(string strFileName)
      {
         string strData = "";
         string strItem = "";
         double dblPrice = 0.0;
         bool blnGotPrice = false;

         try
         {
            StreamReader fileIn = new StreamReader(strFileName);
            while ((!fileIn.EndOfStream) && (!blnGotPrice))
            {
               strData = fileIn.ReadLine();
               if (strData.StartsWith("item:"))
               { //split the string by colon and take the second element
                  strItem = strData.Split(':')[1].Trim();
               }
               else if (strData.StartsWith("price:"))
               {
                  dblPrice = double.Parse(strData.Split(':')[1].Trim());
                  blnGotPrice = true;
               }
            }
            fileIn.Close();
         }
         catch (Exception exc)
         {// if an exception is thrown, the message will be in the receipt
            strItem = exc.Message;
         }

         return new KeyValuePair<string,double>(strItem, dblPrice);
      }

      static void Main(string[] args)
      {
         string strReceiptFile = "../../Grocery Billing.txt";
         KeyValuePair<string, double> kvp = GetOneItemFromReceipt(strReceiptFile);
         Console.WriteLine("Key={0}\tValue={1}", kvp.Key, kvp.Value);
      }
   }
}

If and when you need to read more than one item from the receipt (such as this) :

item: Computer
date of purchase: 12/12/2011
price:823

item: Monitor
date of purchase: 12/12/2011
price:150

item: Monitor
date of purchase: 12/12/2011
price:200

item: Coffee
date of purchase: 12/12/2011
price:8

totalcost:1181

You can return the elements as an ILookup where the key is the item name and the value is the price that will be automatically collected into an Enumerable of the type double (in this case).

The instruction couuld possibly lead you to create a Class that will contain the items read from the receipt including UPC code and other things.

The options are wide-open.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.