-3

I have a small app using Drive.Info. I want to do two things. Check a certain drive exists on a machine, and if it does and todaysdate isn't one of a number of dates stored in a text file, run a small application. If today's date is read inside the text file, do nothing. I Have a bunch of code working but having trouble with the DateTime object. Can anyone take a look at what I have and advise what I need to restructure? All the logic is there, I'm just not putting it together correctly.

  1. Dates stored in the txt file I'm reading from are like so on each line: 25/12/2010.
  2. Inside the catch statement the line "Console.WriteLine(e.Message);" is what is generating the " String was not recognised as a valid DateTime" issue.
  3. My desired goal is: If today's date is NOT found in the text file & The drive specified at the line "(d.Name.Contains("C"))" exists on the current machine, run calc.exe.
  4. If today's date IS found in the text file, do nothing.

My issue is: How do I modify the structure of my application so I can: compare dates successfully with those stored in the txt file. And secondly, adjust my logic so I can achieve parts 3 & 4 above.

Apologies for needing to edit, I should have been more clear with my initial post. Thanks.

EDIT: Guys I've updated the code below. It seems to be working now. Thanks for the help and sorry again for the poorly put together first question. The application behaviour is working as desired now, however; the catch is still being hit (when today's date is not in the file, and the specified drive does not exist) It would be nice to understand why this is happening?

public static void Main()
/* Goal of this application: Read a text file filled with public holiday dates     formatted as: 25/12/2011
 * Compare these to today's date.  If not a match, run calc.exe ASSUMING THE SPECIFIED   DRIVE ON LINE 78
 * IS FOUND ON THE COMPUTER.  If the date matches, do nothing.
*/
{
    Process Calculator = new Process();
    Calculator.StartInfo.FileName = "calc.exe";
    Calculator.StartInfo.Arguments = "ProcessStart.cs";
    DriveInfo[] allDrives = DriveInfo.GetDrives();

    // Create a StreamReader to read from file.
    StreamReader sr = new StreamReader("file.txt");

        String DateFromFile;
        DateTime todaysDate = DateTime.Today;

        try
        {              
            // Read and display lines from the file until the eof is reached.
            while ((DateFromFile = sr.ReadLine()) != null)
            {
                Console.WriteLine(DateFromFile);
                DateTime dt = Convert.ToDateTime(DateFromFile);


                if (dt == todaysDate)
                {
                    Console.WriteLine("File.text has todays date inside! Not gonna run calc.exe");
                    Environment.Exit(0);

                }//end if 

                else
                {
                 }//end else


          }//end while
        }//end try

        catch (Exception e)
        {
            // Let the user know what went wrong.
            Console.WriteLine("The file.txt could not be read");
            Console.WriteLine(e.Message);
       }

        ////////// DO THE REST ///////////
     foreach (DriveInfo d in allDrives)
        {
            Console.WriteLine("Drive {0}", d.Name);

            Console.WriteLine("  File type: {0}", d.DriveType);
            if (d.IsReady == true)
            {
                Console.WriteLine("  Volume label: {0}", d.VolumeLabel);
                Console.WriteLine("  File system: {0}", d.DriveFormat);
                Console.WriteLine(
                    "  Available space to current user:{0, 15} bytes",
                    d.AvailableFreeSpace);

                Console.WriteLine(
                    "  Total available space:          {0, 15} bytes",
                    d.TotalFreeSpace);

                Console.WriteLine(
                    "  Total size of drive:            {0, 15} bytes ",
                    d.TotalSize);
            }//end if
            if (d.Name.Contains("T"))
            {
                Console.WriteLine("\n");
                Console.WriteLine("** SUCCESS - LETTER FOUND **\n\n ** RUN CALC.EXE **");
                Console.WriteLine("\n");
                Calculator.Start();
            }//end if
            else
            {
                Console.WriteLine("** LETTER NOT FOUND **");
                Console.WriteLine("\n");
            }//end else  
        }//end for


}//end main
}//end class
GrumP
  • 1,183
  • 6
  • 19
  • 43
  • What is your date format on text file? – Dor Cohen Apr 10 '12 at 09:17
  • *but having trouble with the DateTime object*, can you expand on that – V4Vendetta Apr 10 '12 at 09:17
  • What is the trouble that you have with the DateTime objecj? Can be provide more details. – Anil Mathew Apr 10 '12 at 09:18
  • Date format is 25/12/2001 on each line of the file there is a new date. When I run the application I get "String was not recognized as a valid DateTime". – GrumP Apr 10 '12 at 09:19
  • 01/01/2001 is not a format, dd/MM/yyyy it is indeed a format – Adrian Iftode Apr 10 '12 at 09:20
  • 2
    well you can use `DateTime.ParseExact` in case your format is fixed ? – V4Vendetta Apr 10 '12 at 09:20
  • 2
    @GrumP - you really should mention any error message. – H H Apr 10 '12 at 09:21
  • Mention line where message throw – SMK Apr 10 '12 at 09:23
  • No error message, the program runs, but in the command window it prints " String was not recognised as as a valid DateTime" It does however print out the contents of the file. – GrumP Apr 10 '12 at 09:30
  • Check the culture the date was written to the file in. For example the date might be written to the file as 04/10/2012, if the machine's culture is US EN then this is 4 Oct otherwise it could be 10 April. To overcome this use DateTime.Parse instead of Convert.ToDateTime. For example: DateTime.Parse(DateFromFile, System.Globalization.CultureInfo.CurrentCulture); It could be the culture changed between writing and reading. – GrantVS Apr 10 '12 at 09:36

3 Answers3

2

Here is the duplicate Question on StackOverflow

String was not recognized as a valid DateTime " format dd/MM/yyyy"

may this help you

Change your code line : DateTime dt = Convert.ToDateTime(DateFromFile);

to

DateTime dt= DateTime.ParseExact(DateFromFile, "dd/MM/yyyy", null);
Community
  • 1
  • 1
SMK
  • 2,098
  • 2
  • 13
  • 21
2

When comparing dates and strings you need to pay attention to 2 things:

  1. Ensuring you're working with the correct data types
  2. Ensuring you're working with the correct formats.

so if you want to compare a DateTime with a string date the first thing you want to do is convert the string to a DateTime.

The best and most reliable way to do this is to know the format of the string upfront and use parseExact like this:

string myDateTimeString = "03/04/2012"; // Notice month and day are ambiguous!
string format = "dd/MM/yyyy";
DateTime dateTime = DateTime.ParseExact(myDateTimeString, format,
        CultureInfo.InvariantCulture);

It is important to use the cultureInfo overload too. Just do it always your code will be more reliable.

Now you have a dateTime you can compare it, but I wouldn't use the equal operator on the base object instead I would use this:

if (myDate.Date == DateTime.Today)
{
   //Occurs on same day!

}

or in your case:

if (myDate.Date == DateFromTextFile.Date)
{
  //Condition met
}
JL.
  • 78,954
  • 126
  • 311
  • 459
0

I think you have to get the current date at the beginning to particular date format.

As e.g. Use

String todaysDate = DateTime.Now.ToShortDateString();

And when you compare also convert the string to that format and compare

 String dt = DateTime.Parse(DateFromFile).ToShortDateString();
las
  • 196
  • 8