If a Folder Does Not Exist, Create It

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 to mkdir only if a directory does not already exist?

Try mkdir -p:

mkdir -p foo

Note that this will also create any intermediate directories that don't exist; for instance,

mkdir -p foo/bar/baz

will create directories foo, foo/bar, and foo/bar/baz if they don't exist.

Some implementation like GNU mkdir include mkdir --parents as a more readable alias, but this is not specified in POSIX/Single Unix Specification and not available on many common platforms like macOS, various BSDs, and various commercial Unixes, so it should be avoided.

If you want an error when parent directories don't exist, and want to create the directory if it doesn't exist, then you can test for the existence of the directory first:

[ -d foo ] || mkdir foo

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.

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.

How to create a directory if it doesn't exist using Node.js

For individual dirs:

var fs = require('fs');
var dir = './tmp';

if (!fs.existsSync(dir)){
fs.mkdirSync(dir);
}

Or, for nested dirs:

var fs = require('fs');
var dir = './tmp/but/then/nested';

if (!fs.existsSync(dir)){
fs.mkdirSync(dir, { recursive: true });
}

Create directory if not exists

The folder may created in your C:\( the default drive where OS is installed). that is folder location is C:\Logs\WZCLogs\. you can confirm that a folder is created somewhere in the drive-by executing the code again, this time the if (!Directory.Exists(FilePath)) returns true. Since you have not specified any location the compiler assumes So. Check whether it is created or not;

You can extend the try Like this:

try
{
Directory.CreateDirectory(FilePath);
}
catch (Exception ex)
{
// handle them here
}

If the path is a wrong one definitely an exception will be thrown; I have tried with "X:\sample" which gives me the exception:

Could not find a part of the path 'X:\sample

Whereas if I tried with Logs\WZCLogs which won't give any exception for the first time and also skip the if for the second time; Hence I found that the folder is created somewhere else;

You can make these changes to make them work:

 string FilePath=Path.Combine(HostingEnvironment.ApplicationPhysicalPath, @"Logs\WZCLogs");

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


Related Topics



Leave a reply



Submit