How to Create a File and Any Folders, If the Folders Don't Exist

If a folder does not exist, create it

Use System.IO.Directory.CreateDirectory.

According to the official ".NET" docs, you don't need to check if it exists first.

System.io   >   Directory   >   Directory.CreateDirectory

Any and all directories specified in path are created, unless they already exist or unless some part of path is invalid. If the directory already exists, this method does not create a new directory, but it returns a DirectoryInfo object for the existing directory.

        — learn.microsoft.com/dotnet/api/



How do I create a file AND any folders, if the folders don't exist?

DirectoryInfo di = Directory.CreateDirectory(path);
Console.WriteLine("The directory was created successfully at {0}.",
Directory.GetCreationTime(path));

See this MSDN page.

Create a directory if it does not exist and then create the files in that directory as well

This code checks for the existence of the directory first and creates it if not, and creates the file afterwards. Please note that I couldn't verify some of your method calls as I don't have your complete code, so I'm assuming the calls to things like getTimeStamp() and getClassName() will work. You should also do something with the possible IOException that can be thrown when using any of the java.io.* classes - either your function that writes the files should throw this exception (and it be handled elsewhere), or you should do it in the method directly. Also, I assumed that id is of type String - I don't know as your code doesn't explicitly define it. If it is something else like an int, you should probably cast it to a String before using it in the fileName as I have done here.

Also, I replaced your append calls with concat or + as I saw appropriate.

public void writeFile(String value){
String PATH = "/remote/dir/server/";
String directoryName = PATH.concat(this.getClassName());
String fileName = id + getTimeStamp() + ".txt";

File directory = new File(directoryName);
if (! directory.exists()){
directory.mkdir();
// If you require it to make the entire directory path including parents,
// use directory.mkdirs(); here instead.
}

File file = new File(directoryName + "/" + fileName);
try{
FileWriter fw = new FileWriter(file.getAbsoluteFile());
BufferedWriter bw = new BufferedWriter(fw);
bw.write(value);
bw.close();
}
catch (IOException e){
e.printStackTrace();
System.exit(-1);
}
}

You should probably not use bare path names like this if you want to run the code on Microsoft Windows - I'm not sure what it will do with the / in the filenames. For full portability, you should probably use something like File.separator to construct your paths.

Edit: According to a comment by JosefScript below, it's not necessary to test for directory existence. The directory.mkdir() call will return true if it created a directory, and false if it didn't, including the case when the directory already existed.

Automatically create folders if does not exists in C#

The simpelest solution is replace

using (FileStream fs = new FileStream(filePath, FileMode.OpenOrCreate))

with

System.IO.Directory.CreateDirectory(filePath)

That will create the directory if it does not exist or do nothing if it does.

How do I create directory if it doesn't exist to create a file?

To Create

(new FileInfo(filePath)).Directory.Create() before writing to the file.

....Or, if it exists, then create (else do nothing)

System.IO.FileInfo file = new System.IO.FileInfo(filePath);
file.Directory.Create(); // If the directory already exists, this method does nothing.
System.IO.File.WriteAllText(file.FullName, content);

Create intermediate folders if one doesn't exist

You have to actually call some method to create the directories. Just creating a file object will not create the corresponding file or directory on the file system.

You can use File#mkdirs() method to create the directory: -

theFile.mkdirs();

Difference between File#mkdir() and File#mkdirs() is that, the later will create any intermediate directory if it does not exist.

Checking folder and if it doesn't exist create it

If you want to create a folder inside a second folder or check the existence of them you can use builtin os library:

import os

PATH = 'folder_1/folder_2'
if not os.path.exists(PATH):
os.makedirs(PATH)

os.makedirs() create all folders in the PATH if they does not exist.

Write file to a directory that doesn't exist

You need to first create the directory.

The mkdir -p implementation from this answer will do just what you want. mkdir -p will create any parent directories as required, and silently do nothing if it already exists.

Here I've implemented a safe_open_w() method which calls mkdir_p on the directory part of the path, before opening the file for writing:

import os, os.path
import errno

# Taken from https://stackoverflow.com/a/600612/119527
def mkdir_p(path):
try:
os.makedirs(path)
except OSError as exc: # Python >2.5
if exc.errno == errno.EEXIST and os.path.isdir(path):
pass
else: raise

def safe_open_w(path):
''' Open "path" for writing, creating any parent directories as needed.
'''
mkdir_p(os.path.dirname(path))
return open(path, 'w')

with safe_open_w('/Users/bill/output/output-text.txt') as f:
f.write(...)

Updated for Python 3:

import os, os.path

def safe_open_w(path):
''' Open "path" for writing, creating any parent directories as needed.
'''
os.makedirs(os.path.dirname(path), exist_ok=True)
return open(path, 'w')

with safe_open_w('/Users/bill/output/output-text.txt') as f:
f.write(...)


Related Topics



Leave a reply



Submit