我仅在以下情况下才尝试创建文件:所定位的路径中不存在该文件,并且我猜该目录也存在;如果该文件已经存在,则我不让用户继续使用,因此该应用程序关闭。我尝试执行此操作,但似乎当我指定位置时会告诉我文件不存在时该文件存在。
this.path = @output;
this.path2File = @output + "\\" + type + "tobearchived.txt";
if (!Directory.Exists(path) && !File.Exists(path2File))
{
File.Create(path2File);
}
else
{
Console.WriteLine("Error: File Already Exists. Press any key to exit.");
Console.ReadKey();
Environment.Exit(0);
}
}
您的IF条件似乎有问题,请尝试以下操作;否则,请执行以下操作。
if (Directory.Exists(path) && File.Exists(path2File))
{
Console.WriteLine("Error: File Already Exists. Press any key to exit.");
Console.ReadKey();
Environment.Exit(0);
}
else
{
File.Create(path2File);
}
编辑:您的代码中的问题是,假设该目录存在,但文件不存在。然后'!Directory.Exists(path)'为'false',由于AND条件,它将跳过对'File.Exists(path2File)'的检查。因此,控制将直接进入代码的“其他”部分。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句