I have made a program in c# where the user will input some data and that program should prompt the user to specify the date to view all the appointments of that day.i have made the code but still the problem lies is i can only find that the date which is entered by the user is there in the file but i dont dont know how to display the data related to it please help me..the code is as follow

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


namespace FileData
{
    class Program
    {
        DateTime date = new DateTime();
        DateTime time = new DateTime();

        string name;
        public void Inputdata()
        {
            FileStream fs = new FileStream("C:\\Data.txt",FileMode.Append,FileAccess.Write,FileShare.Write);
            StreamWriter sw = new StreamWriter(fs);

            Console.WriteLine("Enter the date in format {dd/mm/yyyy} :: ");
            date = DateTime.Parse(Console.ReadLine());
            sw.WriteLine("-------------------------------------------");
            sw.WriteLine("Date :: "+date);
           

            Console.WriteLine("Enter the name of the person you want to meet :: ");
            name = Console.ReadLine();
            sw.WriteLine("Name of the person :: "+name);
           

            Console.WriteLine("Enter the your visit time in format {HH:MM:SS} :: ");
            time = DateTime.Parse(Console.ReadLine());
            sw.WriteLine("Visit time :: "+time);
            sw.WriteLine("-------------------------------------------\n");
            sw.Close();
           // sw.Flush();
            fs.Close();
        }
        public void Displaydata()
        {
            FileStream fs1 = new FileStream("C:\\Data.txt", FileMode.Open, FileAccess.Read, FileShare.Read);
            StreamReader sr = new StreamReader(fs1);
            sr.BaseStream.Seek(0, SeekOrigin.Begin);

            string r1 = sr.ReadLine();
            Console.WriteLine("File Data :: \n");
            //Console.WriteLine("\n");
            while (r1 != null)
            {
                Console.WriteLine("{0}", r1);
                
                r1 = sr.ReadLine();
            
            }
           // Console.WriteLine(r1);

            sr.Close();
            fs1.Close();
        }

        public void search()
        {
            string fName = @"C:\Data.txt ";
            StreamReader testTxt = new StreamReader(fName);
            string allRead = testTxt.ReadToEnd();
             
            Console.WriteLine("Enter the date in format {dd/mm/yyyy} :: ");
            DateTime search1 = new DateTime(); 
            string s =  search1.ToString(Console.ReadLine());
            
       
            if (allRead.Contains(s))
            {
               Console.WriteLine("Found");
             
            }
            else
            {
                Console.WriteLine("not found");
            }

            testTxt.Close();
        }
        static void Main(string[] args)
        {
            Program p = new Program();
          

            Console.WriteLine("1. Enter a data into file  ");
            Console.WriteLine("2. View the data from file  ");
            Console.WriteLine("3. Search according to date  ");
            Console.WriteLine("4. Exit \n");
            Console.WriteLine("Enter your choice :: ");
            int a = Convert.ToInt32(Console.ReadLine());

            switch (a)
            {

                case 1: p.Inputdata();
                    break;
                case 2: p.Displaydata();
                    break;
                case 3: p.search();
                    break;
                case 4: System.Environment.Exit(0);
                    break;

                default: Console.WriteLine("Please enter the correct choice");
                    break;
            }

            Console.ReadLine();
        }
    }
}
while (r1 != null)
{
   Console.WriteLine("{0}", r1);
   r1 = sr.ReadLine();
}

the code above, taken from your program, loops through and gets each line in the file. You allready know how to seach for the date. Combine these two things!

that's right but i need to find the data related to that particular date entered by the user not all the data.

Well you know how many lines the input should be (3 if I read it properly):

  1. Date
  2. Name
  3. Time

Soo....

If I were you I would take the line with the found date and the following 2 lines and input them into 3 corresponding variables.

i.e.:

  1. Found Date on Line 4
  2. Line 4 input into fDate variable
  3. Line 5 input into fName variable
  4. Line 6 input into fTime variable

Those would be the steps, the coding shouldn't be too much of a stretch from there :twisted:

Hope that helps, please remember to mark the thread solved once your issue is resolved.

i dint get u what you are saying....?there are not only three entries over there, there are many n out of that the user will enter the date n i have to find the data related to that date that means 1. The date
2. The person name
3. The visit time

"that's right but i need to find the data related to that particular date entered by the user not all the data. "

yes, modify the seaching through all the data, perhaps by adding an if statement?

while( go through each line of data)
{
    //instead, as before, of printing out every line:
    if ( search line for date == date user wants)
    {
        print out/save data on this line (and next x lines, depending on how many lines
        your data takes up in the file
    }
}

its not possible i have tried a lot......i get all the data printed on console..

OK... I'll try again...

You used:

Console.WriteLine("Enter the date in format {dd/mm/yyyy} :: ");
            date = DateTime.Parse(Console.ReadLine());
            sw.WriteLine("-------------------------------------------");
            sw.WriteLine("Date :: "+date); // User Input Date
           

            Console.WriteLine("Enter the name of the person you want to meet :: ");
            name = Console.ReadLine();
            sw.WriteLine("Name of the person :: "+name); // User Input Name
           

            Console.WriteLine("Enter the your visit time in format {HH:MM:SS} :: ");
            time = DateTime.Parse(Console.ReadLine());
            sw.WriteLine("Visit time :: "+time); // User Input Time
            sw.WriteLine("-------------------------------------------\n");
            sw.Close();

Now, personally... Where you have the following:

public void search()
        {
            string fName = @"C:\Data.txt ";
            StreamReader testTxt = new StreamReader(fName);
            string allRead = testTxt.ReadToEnd();
             
            Console.WriteLine("Enter the date in format {dd/mm/yyyy} :: ");
            DateTime search1 = new DateTime(); 
            string s =  search1.ToString(Console.ReadLine());
            
       
            if (allRead.Contains(s))
            {
               Console.WriteLine("Found");
             
            }
            else
            {
                Console.WriteLine("not found");
            }

            testTxt.Close();
        }

I would do the following instead:

public void search()
        {
            string fName = @"C:\Data.txt ";
            StreamReader testTxt = new StreamReader(fName);
            // string allRead = testTxt.ReadToEnd();
             
            Console.WriteLine("Enter the date in format {dd/mm/yyyy} :: ");
            DateTime search1 = new DateTime(); 
            string s =  search1.ToString(Console.ReadLine());
            r2 = testTxt.ReadLine()
            bool found = false;
            while (r2 != null && found == false)
            {
                if (r2.Contains(s))
                {
                    Console.WriteLine("found");
                    string tmpRead = "";
                    Console.WriteLine("{0}", r2); // Print Date Found
                    tmpRead = testTxt.ReadLine(); // Read Next Line and Print Name
                    Console.WriteLine("{0}", tmpRead);
                    tmpRead = testTxt.ReadLine(); // Read Next Line and Print Time
                    Console.WriteLine("{0}", tmpRead);
                    found == true
                }
            }
            else
            {
                Console.WriteLine("not found");
            }

            testTxt.Close();
        }

The only drawback to this method being that it will display the first record for a given date only. Should there be multiple records for a given date you will not get the additional records unless you do additional checks as follows:

  1. Check first for number of matches to requested date
  2. Loop through records starting from end of previous 'found' record until match counter = 0

I hope that's more helpful and not too difficult to follow :)

let see if this code works i will also try my best to more work on this .....thanks for your help guys......

I just hope it was more helpful the way I put it the 2nd time (and that I didn't botch the loop/condition)... it took me the length of 2 replies and 1 edit to your first reply to type it all out lol.

still thanks guys......i am new to c sharp.n never worked with filestream n all

You'll need to fix the following as well as implementing your search:

DateTime search1 = new DateTime();
string s =  search1.ToString(Console.ReadLine());

You have misused the overload of ToString. Where you have passed it Console.Readline() the method is expecting a format string to determine how to construct the string.
You need to parse the console input into search1 first and then call .ToString().
I feel i ought to mention, however, that unless you plan to use search1 elsewhere, you could skip it altogether and just use string s = Console.ReadLine(); EDIT: I'll rephrase that..you ought ot fix it. Apparently the output is correct, but it is not the intended use of the method and may have unexpected results down the line.

You'll need to fix the following as well as implementing your search:

DateTime search1 = new DateTime();
string s =  search1.ToString(Console.ReadLine());

I'll rephrase that..you ought ot fix it. Apparently the output is correct, but it is not the intended use of the method and may have unexpected results down the line.

Actually, I'm surprised I missed that myself.

Realistically, unless he's converting the info in the text file to dateTime format for local variable comparison, the dateTime portion doesn't need to exist at all and can entirely be handled by strings. The only place where he would need dateTime is if he was working with a webform or windows form where the inputs would possibly be coming from a date/time picker. In console it's all text and can be done entirely with strings.

Yup, as i said, he can just use string s = Console.ReadLine(); :)

I did a little reading and confirmed that any character in the format string that isn't one of the recognised format characters (eg dd, mm, YYYY, etc) is treated as a literal and output "as is" which is why the result is "correct". It treats the input as a whole bunch of literals and seperators so it spits out the input unchanged.
The ends don't justify the means; its still not the intended use so I would still correct it; plus, your passing the string through a method to get the same string out the other side so its redundant overhead.

is it possible that we can retrieve the in-between data
example:there are this many data in file
Date :: 10/09/2010
Name :: Abc
Visit Time :: 10:50 AM

Date :: 12/09/2010
Name :: def
Visit Time :: 09:50 AM

Date :: 13/09/2010
Name :: xyz
Visit Time :: 08:50 AM

Date :: 14/09/2010
Name :: pqr
Visit Time :: 10:50 PM

can we retrieve data like
Date :: 12/09/2010
Name :: def
Visit Time :: 09:50 AM

from between the file......

Since you have read the whole file into a string and checked that your date exists you could split the string into an array and iterate through each line:

string allRead = testTxt.ReadToEnd();

string[] allLines = allText.Split(Environment.NewLine.ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
for (int i = 0; i < allLines.Length; i++)
{
    //check allLine[i] for search data
    //process lines when found
}

hey can any one explain me how this line will execute

string[] allLines = allText.Split(Environment.NewLine.ToCharArray(), StringSplitOptions.RemoveEmptyEntries);

hey can any one explain me how this line will execute

string[] allLines = allText.Split(Environment.NewLine.ToCharArray(), StringSplitOptions.RemoveEmptyEntries);

Having no idea, I would guess that string.Split(x,y) splits the string at every character x, with the following options y

Environment.NewLine is the newline object, represented by Environment.NewLine.ToCharArray(), so you want to split it at every new line (/n i assume)

StringSplitOptions are the options for string splitting (!), the RemoveEmptyEntries removes empty entries (lines inthis case).

For an input file of

hello
the brown
fox jumped

bye!

represented by "hello\nthe brown\nfox jumped\n\n\nbye!"

you would get a string array allLines, of:

allLines[0] = hello;
allLines[1] = the brown
allLines[2] = fox jumped
allLines[3] = bye!

Of course, I have never used string.split so i dont know if this is correct! take a look at the documentation - or test it with your own string and see what happens

commented: very astute...you've reasoned out exactly what is going on :) +3

If you ever come across a method or concept you dont understand, msdn is usually a great place to start.
The method above is an overload of the string.split method. It accepts an array of chars that it will use to delimit the results of the split and a value of the enum StringSplitOptions, in this case the option to remove empty strings from the results.
When run, it will split the string into an array of smaller strings based on the characters you passed it.
Heres an example:

static void Main(string[] args)
    {
        string stringToSplit = "a,b,c,d,e,f"; //string to be split
        string[] arrayOfSplitStrings; //array to store result
        char[] delimiters = { ',' }; //array of values to mark end of each substring
        arrayOfSplitStrings = stringToSplit.Split(delimiters, StringSplitOptions.RemoveEmptyEntries); 

        foreach (string s in arrayOfSplitStrings)
        {
            Console.WriteLine(s);
        }

        Console.ReadKey();

    }

Output will be:
a
b
c
d
e
f

Notice that the blank string between e and f is removed by the StringSplitOptions.
Every time the String.Split method finds one of the characters in the delimiter array it moves the characters before the delimiter into a new substring in the array.

thanks guys...

Finally got the output which i was looking for......and thanks for the help guys....:-)

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

namespace FileData
{
    class Program
    {
        DateTime date = new DateTime();
        DateTime time = new DateTime();
        string name;

       public void InputData()
        {
            FileStream fs = new FileStream("C:\\Data.txt", FileMode.Append, FileAccess.Write, FileShare.Write);
            StreamWriter sw = new StreamWriter(fs);

            Console.WriteLine("Enter the date in format in {DD/MM/YYYY} ");
            date = DateTime.Parse(Console.ReadLine());
            sw.WriteLine("Date :: {0} ", date);

            Console.WriteLine("Enter the name of teh person you want top visit to ::  ");
            name = Console.ReadLine();
            sw.WriteLine("Persons Name :: {0}", name);

            Console.WriteLine("Enter the time of your visit in format {HH:MM} ");
            time = DateTime.Parse(Console.ReadLine());
            sw.WriteLine("Your visit Time  :: {0}", time);
            sw.WriteLine("\n");

            sw.Close();
            fs.Close();
        }

       public void DisplayData()
        {
            FileStream fs1 = new FileStream("C:\\Data.txt", FileMode.Open, FileAccess.Read, FileShare.Read);
            StreamReader sr = new StreamReader(fs1);
            sr.BaseStream.Seek(0, SeekOrigin.Begin);
            string r1 = sr.ReadLine();
            while (r1 != null)
            {
                Console.WriteLine(" {0} ", r1);
                r1 = sr.ReadLine();
            }
            sr.Close();
            fs1.Close();
        }

    public void Search()
    {
        StreamReader testTxt = new StreamReader("C:\\Data.txt");
        string s1 = testTxt.ReadLine();
        testTxt.BaseStream.Seek(0, SeekOrigin.Begin);
        Console.WriteLine("Enter the date you want the data from in format {DD/MM/YYYY} :: ");
        DateTime search1 = new DateTime();
        string r2 = search1.ToString(Console.ReadLine());
        bool found = false;
        try
        {
        while (s1 != null)
         {
              s1 = testTxt.ReadLine();
                if (s1.Contains(r2))
                 {
                  while (r2 != null && found == false)
                   {

                        string tempRead = "";
                        Console.WriteLine();
                        Console.WriteLine("Date :: {0}", r2);
                        tempRead = testTxt.ReadLine();
                        Console.WriteLine("{0}", tempRead);
                        tempRead = testTxt.ReadLine();
                        Console.WriteLine("{0}", tempRead);
                        found = true;
                    }
                }
                else
                {
                    Console.Write("");
                }
            }
        }
        catch (Exception e)
        {

        }
        testTxt.Close();
    }


        static void Main(string[] args)
        {
            Program p = new Program();
            char b;
            do
            {
                Console.WriteLine("1 :: Add Appointment");
                Console.WriteLine("2 :: View Appointment");
                Console.WriteLine("3 :: Search");
                Console.WriteLine("4 :: Exit");

                Console.WriteLine("Enter your choice :: ");
                int a = Convert.ToInt32(Console.ReadLine());

                switch (a)
                {
                    case 1: p.InputData();
                        break;
                    case 2: p.DisplayData();
                        break;
                    case 3: p.Search();
                        break;
                    case 4: System.Environment.Exit(0);
                        break;
                    default: Console.WriteLine();
                        break;
                }
                Console.WriteLine();
                Console.WriteLine("Do you want to enter the another choice press {Y/N}");
                b = Convert.ToChar(Console.ReadLine());

            } while (b == 'y' || b == 'Y');
            Console.WriteLine("\n");

        }
    }
}

in the above code ..is there any other way to do this program.or else is there any other way the program can me made more flexible.

in the above code ..is there any other way to do this program.or else is there any other way the program can me made more flexible.

Are you doing it to learn? I would try to improve it by taking it to the next level a little bit - try reading the data into an "apointment" class, and making an object to hold all the appointments.

You can make this object search and alter apointments and have a "save" function to save them in the appropriate way and a "load" function to fill itself with information from the file, this is much more flexible for searching and other functions later on, the file only has to be accessed once.

Just an idea of what you could do next!

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.