Mike Sportsman
Mike Sportsman

Reputation: 120

How to create an empty folder when a file with the folder's name already exists?

I am sure there is something simple that I am overlooking here but I have never ran into this problem before and I cannot seam to find the cause of the problem.

This an example of the root directory on my hard-drive:

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 )

The code I want to use to create a new folder is this method:

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

Does anyone see what is wrong here? Please help and thank you!

Upvotes: 3

Views: 1279

Answers (1)

Lasse V. Karlsen
Lasse V. Karlsen

Reputation: 391664

You can't.

You can't have two file system entries with the same name.

So either:

  1. Delete the file, then reuse the old name for the new directory
  2. Rename the file, then reuse the old name for the new directory
  3. Create the directory with a different name

Note that NTFS has its roots in POSIX, and POSIX allows multiple file system entries that differ by case, because the file system is case sensitive regarding object names. NTFS inherited this trait, but Win32 will block you from doing this. Using Win32 it is thus not possible to create a file called X together with a file called x in the same directory, but using lower level system calls it may be possible.

See https://superuser.com/questions/364057/why-is-ntfs-case-sensitive for more information on this topic.

However, identical names for multiple file system entries is not allowed and never has been.

Upvotes: 8

Related Questions