Creating a File that the Path does not exists?

39,497

Solution 1

Try

Directory.CreateDirectory(@"C:\MyApp\MySubDir\Data")

http://www.devx.com/vb2themax/Tip/18678

Solution 2

Given that you've the full path (Folder + File name), the following code will ensure your required directory path exists (if it does not exist already)

        FileInfo fileInfo = new FileInfo(fileFullPath);

        if (!fileInfo.Exists)
            Directory.CreateDirectory(fileInfo.Directory.FullName);


        //create the file ...

Solution 3

below should also work

    FileInfo fileInfo = new FileInfo(fileFullPath);
    if (!fileInfo.Directory.Exists) fileInfo.Directory.Create()

work on directory of fileinfo, rather than static directory class

Solution 4

You will need to create the Directory first. It will create all of the subdirectories that don't exist within the path you send it. It's quite a powerful piece of functionality.

Directory.CreateDirectory(filePath);

If you don't know whether the directory exists or not you can use Directory.Exists. But not for this case as it would be pointless. MSDN states that CreateDirectory does nothing if the directory currently exists. But if you wanted to check existance of the directory for another reason you can use:

  if(Directory.Exists(folder) == false)
    {
    //do stuff  
    }

Solution 5

Directory.CreateDirectory("path");
Share:
39,497

Related videos on Youtube

Athiwat Chunlakhan
Author by

Athiwat Chunlakhan

https://www.athiwat.xyz/

Updated on July 09, 2022

Comments

  • Athiwat Chunlakhan
    Athiwat Chunlakhan almost 2 years

    I just can't get around this. I am able to create a file with File.Create... File.CrateText and so on, only if the path exists. If it does not the file will not we written and returns an error. How do I create the path?

  • Bdiem
    Bdiem over 14 years
    As this post mostlikely solves your problem here the additional MSDN information: msdn.microsoft.com/en-us/library/as2f1fez.aspx
  • Athiwat Chunlakhan
    Athiwat Chunlakhan over 14 years
    And how do we check if the path exists? or we just call this function.
  • Bdiem
    Bdiem over 14 years
    READ! MSDN Says: If the folder already exists, CreateDirectory does nothing.
  • Daniel Elkington
    Daniel Elkington over 5 years
    This won't work if the filePath is a full path (folder + file name) - it'll annoyingly create a directory with the name of your desired file (eg if filePath is pathTo\helloWorld.txt it'll create a folder named helloWorld.txt inside the folder pathTo).
  • Shambhu Kumar
    Shambhu Kumar over 5 years
    @DanielElkington are you sure about that?
  • Daniel Elkington
    Daniel Elkington over 5 years
    I tested this the other day and that’s what happened. Ashraf Alam’s answer using the FileInfo class to split out the directory name worked. But if you know the path is only a directory then this will work.