我有以下代码,可以很好地工作。我尝试做的事情(在一个镜头中)是检查目录是否存在,如果存在,我想检查文件夹中是否存在文件。如果是,则返回Y,否则返回N:
string s = new DirectoryInfo("C:\\EXP_Reports\\36000").Exists
? new DirectoryInfo("C:\\EXP_Reports\\36000").GetFiles("EXP Report #36001.pdf")
.Any() ? "Y" : "N"
: "N";我想知道上面的代码是否可以进一步优化。请注意,我想用一句话来做这件事。
发布于 2013-01-29 01:51:35
为什么不简单地使用File.Exists。
bool q = File.Exists(@"C:\EXP_Reports\36000\EXP Report #36001.pdf");请参阅http://msdn.microsoft.com/en-us/library/system.io.file.exists.aspx
我还更改了代码,使用bool而不是包含Y或N的string。
而且,使用原封不动的字符串文字@"..."读起来更好。
发布于 2013-01-29 01:53:06
使用
System.IO.Directory.Exists("...");
和
System.IO.File.Exists("...");
不需要实例化任何东西。
如果只需要检查文件是否存在,则不需要检查目录是否存在。
发布于 2013-01-29 01:53:08
你不能使用string s = File.Exists("C:\\EXP_Reports\\36000\\EXP Report #36001.pdf") ? "Y" : "N";吗?
https://stackoverflow.com/questions/14568037
复制相似问题