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

时间:2014-01-20 13:43:13

标签: c# file io path directory

我确信有一些简单的东西我在这里可以忽略,但我以前从未遇到过这个问题,我无法找到问题的原因。

这是我硬盘驱动器上根目录的一个示例:

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 )

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

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 );
         }
      }

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

1 个答案:

答案 0 :(得分:8)

你不能。

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

所以:

  1. 删除该文件,然后将旧名称重新用于新目录
  2. 重命名该文件,然后将旧名称重新用于新目录
  3. 使用其他名称创建目录
  4. 请注意,NTFS的根源在于POSIX,POSIX允许多个文件系统条目因大小写而异,因为文件系统对于对象名称区分大小写。 NTFS继承了这个特性,但是Win32会阻止你这样做。因此,使用Win32无法在同一目录中创建名为X的文件和名为x的文件,但可能使用较低级别的系统调用。

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

    但是,不允许使用多个文件系统条目的相同名称,而且从未使用过相同的名称。

相关问题