【发布时间】:2012-04-10 09:13:10
【问题描述】:
我有一个使用 Drive.Info 的小应用程序。我想做两件事。检查机器上是否存在某个驱动器,如果存在并且 todaysdate 不是存储在文本文件中的多个日期之一,请运行一个小型应用程序。如果在文本文件中读取今天的日期,则什么也不做。我有一堆代码在工作,但在使用 DateTime 对象时遇到了问题。任何人都可以看看我有什么并建议我需要重组什么吗?所有的逻辑都在那里,我只是没有正确地组合起来。
- 存储在我正在读取的 txt 文件中的日期在每个文件中都是如此 线路:2010 年 12 月 25 日。
- 在 catch 语句中的行“Console.WriteLine(e.Message);”是什么产生了“字符串未被识别为有效的日期时间”问题。
- 我想要的目标是:如果在文本文件中找不到今天的日期,并且在当前机器上存在“(d.Name.Contains(“C”))”行中指定的驱动器,请运行 calc.exe。
- 如果在文本文件中找到今天的日期,则什么也不做。
我的问题是:如何修改应用程序的结构,以便:成功地将日期与 txt 文件中存储的日期进行比较。其次,调整我的逻辑,这样我就可以实现上面的第 3 部分和第 4 部分。
很抱歉需要编辑,我最初的帖子应该更清楚。 谢谢。
编辑:伙计们,我已经更新了下面的代码。它现在似乎正在工作。感谢您的帮助,再次为第一个问题的糟糕组合感到抱歉。但是,应用程序行为现在可以正常工作;问题仍然存在(当今天的日期不在文件中,并且指定的驱动器不存在时)很高兴了解为什么会发生这种情况?
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
【问题讨论】:
-
文本文件的日期格式是什么?
-
但在使用 DateTime 对象时遇到问题,您能否进一步扩展
-
您对 DateTime 对象有什么问题?可以提供更多细节。
-
如果您的格式是固定的,您可以使用
DateTime.ParseExact吗? -
@GrumP - 你真的应该提到任何错误信息。