-2

请帮我比较两个文本文件中的日期和时间,并比较以检查它们是否相同,使用DateTime.TryParse方法或任何其他方法。

我有以下代码:

        String[] file1Lines = File.ReadAllLines("Text.txt");
        String[] file2Lines = File.ReadAllLines("Text2.txt");

        for (int i = 0; i < Math.Max(file1Lines.Length, file2Lines.Length); i++)
        {
            if (i > file1Lines.Length)
                /* missing from file 1 */
                Console.WriteLine("Missing from File 1");
            else if (i > file2Lines.Length)
                /* missing from file 2); */
               Console.WriteLine("Missing from File 1") ;
            else if (file1Lines[i].Equals(file2Lines[i]))
                /* lines are equal */
               Console.WriteLine("Lines are equal") ;
            else
                /* lines are different */

                Console.WriteLine("Lines are different");
        }
4

1 回答 1

0

假设您需要以下内容:

    String[] file1Lines = File.ReadAllLines("Text.txt");
    String[] file2Lines = File.ReadAllLines("Text2.txt");

    for (int i = 0; i < Math.Max(file1Lines.Length, file2Lines.Length); i++)
    {
        if (i > file1Lines.Length)
            /* missing from file 1 */
            Console.WriteLine("Missing from File 1");
        else if (i > file2Lines.Length)
            /* missing from file 2); */
           Console.WriteLine("Missing from File 1") ;
        else {
            DateTime file1Date = DateTime.Now;
            DateTime file2Date = DateTime.Now;
                            // try parse a line from first file
            if(DateTime.TryParse(file1Lines[i], out file1Date)) {
                                  // try parse a line from second file
                if( DateTime.TryParse(file2Lines[i], out file2Date)) {
                    if (file1Date.Date == file2Date.Date) {
                        /* lines are equal */
                        Console.WriteLine("Dates are equal") ;
                    } else {
                        /* lines are different */
                        Console.WriteLine("Dates are different");
                    }
                } else {
                    Console.WriteLine("Line in file 2 is not a date") ;
                }                   
            } else {
                Console.WriteLine("Line in file 1 is not a date") ;
            }
        }
    }
于 2013-05-09T09:13:52.483 回答