如果已存在具有文件夹名称的文件,如何创建空文件夹?

Mik*_*man 3 c# directory io file path

我确信有一些简单的东西,我在这里忽略,但我从来没有遇到过这个问题,我不能找到问题的原因.

这是我硬盘上根目录的一个例子:

C:\Folder-1          ( this is a folder )
C:\Folder-2          ( this is a folder )
C:\somename          ( this is a file with no extension )
c:\somename.txt      ( this is a file with an extension )
Run Code Online (Sandbox Code Playgroud)

我想用来创建一个新文件夹的代码是这个方法:

static void Main( string[] args )
{
    try
    {
        // try to create a folder in a directory 
        // where a file with the same name exsists
        createDirectory( "c:\somename" );
    }
    catch
    {
       // this catches an exception "Cannot create directory, because it already exsist
    }
}

private static void createDirectory(string filePath)
      {
         string directoryPath = Path.GetDirectoryName(filePath);

         // if the directory path does not exsists then create it
         if (!Directory.Exists(directoryPath))
         {
            Directory.CreateDirectory(directoryPath );
         }
      }
Run Code Online (Sandbox Code Playgroud)

有谁看到这里有什么问题?请帮助,谢谢!

ang*_*son 8

你不能.

您不能拥有两个具有相同名称的文件系统条目.

所以要么:

  1. 删除该文件,然后将旧名称重新用于新目录
  2. 重命名该文件,然后重新使用旧名称作为新目录
  3. 使用其他名称创建目录

请注意,NTFS的根源在于POSIX,POSIX允许多个文件系统条目因大小写而异,因为文件系统对于对象名称区分大小写.NTFS继承了这个特性,但Win32会阻止你这样做.因此,使用Win32无法创建Xx在同一目录中调用的文件一起调用的文件,但使用较低级别的系统调用可能是可能的.

有关此主题的更多信息,请参阅https://superuser.com/questions/364057/why-is-ntfs-case-sensitive.

但是,不允许使用多个文件系统条目的相同名称.