简体   繁体   English

Directory.Exists()无法识别不存在的文件夹(反斜杠错误)

[英]Directory.Exists() fails with to recognize nonexistent folder (backward slash error)

I am using Directory.Exists() to check the existence of a folder, and encounter a failure of that method. 我正在使用Directory.Exists()来检查文件夹的存在,并且遇到该方法的故障。 My command is: 我的命令是:

if (Directory.Exists(myFolder) == false) 
{ 
    MessageBox.Show(myFolder, "Invalid Log Folder path", MessageBoxButtons.OK, MessageBoxIcon.Hand); 
}

if (Directory.Exists(myFolder) == true) 
{ 
     MessageBox.Show(myFolder, "Valid Folder path"); 
}

When myFolder is C:\\Documents and Settings\\UserID\\My Documents it returns TRUE . 当myFolder为C:\\Documents and Settings\\UserID\\My Documents它返回TRUE

When myFolder is C:\\Documents and Settings\\xxx\\My Documents it returns FALSE (given that xxx does not exist). 当myFolder为C:\\Documents and Settings\\xxx\\My Documents它返回FALSE (假设xxx不存在)。

However, when myFolder is C:\\\\Documents and Settings\\UserID\\My Documents it also returns TRUE . 但是,当myFolder为C:\\\\Documents and Settings\\UserID\\My Documents它也会返回TRUE

The double backward slashes next to C: must have invalidated the test. C:旁的双反斜杠必须使测试无效。 However, Directory.Exists() fails to recognize that. 但是, Directory.Exists()无法识别它。

With more \\ it still encounters the same problem. 使用更多\\仍然会遇到相同的问题。

I just cannot understand how this failure occurs. 我只是不明白这种失败是如何发生的。 I am using VS2008 with .NET 3.5. 我正在将VS2008与.NET 3.5配合使用。

Try this: 尝试这个:

  1. Open command prompt 打开命令提示符
  2. enter the command cd c:\\\\\\\\\\\\\\\\\\ 输入命令cd c:\\\\\\\\\\\\\\\\\\

You will find it's perfectly acceptable. 您会发现它完全可以接受。

Another test: 另一个测试:

  1. Open command prompt 打开命令提示符
  2. try cd c:\\\\\\\\\\\\\\\\\\\\\\\\temp 尝试cd c:\\\\\\\\\\\\\\\\\\\\\\\\temp

You will now be in the c:\\temp directory, assuming you have one. 现在,假设您有一个目录,您将位于c:\\ temp目录中。

Last one: 最后一个:

  1. Open command prompt 打开命令提示符
  2. Try cd c:\\\\\\\\\\\\\\\\\\\\\\\\\\inetpub\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\logs 尝试cd c:\\\\\\\\\\\\\\\\\\\\\\\\\\inetpub\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\logs

You are now in the c:\\inet\\logs directory, assuming you have one. 假设您已有一个,则现在位于c:\\ inet \\ logs目录中。

It seems you had incorrect expectations about how the Directory.Exists() method behaves. 似乎您对Directory.Exists()方法的行为有不正确的期望。

Any number of '\\' is interpretted as a single '\\' in commands and those methods, and is perfectly acceptable input. 在命令和那些方法中,任意数量的“ \\”都被解释为单个“ \\”,并且是完全可以接受的输入。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM