-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
4

3 回答 3

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);
于 2012-04-10T09:18:54.907 回答
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
}
于 2012-04-10T09:54:58.973 回答
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();
于 2012-04-10T09:26:31.963 回答