Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create a file from a path, creating subdirectories if they not exists

Tags:

.net

file

In config of my app I've a path, for example "logs\updater\updater.log"

Starting the app, I want to create the file updater.log, creating all subfolders if they not exists.

So, if tomorrow my user changes the path in config to "logs\mypathisbetter\updater.log", my app continues to work, writing log to the new file.

File.Create, FileInfo.Create, Streamwriter.Create or so: they do that?

Or do I need to check if folders exists, before?

I can't find a clear answer to this question on the net.

like image 770
Ferdinando Santacroce Avatar asked Sep 28 '10 15:09

Ferdinando Santacroce


People also ask

How do you create a directory if it does not exist in Java?

Create a Directory if it Does Not Exist You can use the Java File class to create directories if they don't already exists. The File class contains the method mkdir() and mkdirs() for that purpose. The mkdir() method creates a single directory if it does not already exist.

How do you create a directory if it does not exist in Python?

import os path = '/Users/krunal/Desktop/code/database' os. makedirs(path, exist_ok=False) print("The new directory is created!") So that's how you easily create directories and subdirectories in Python with makedirs(). That's it for creating a directory if not exist in Python.

Which command will create the parent directories as well if not available?

A parent directory is a directory that is above another directory in the directory tree. To create parent directories, use the -p option. When the -p option is used, the command creates the directory only if it doesn't exist.

Does mkdir create file?

When mkdir fails, it doesn't create nothing. But it creates a file. There's no problems to have a file and a folder with the same name in the same directory. In addition, the script now stops on the directory, that doesn't have a file near itself with the same name.


1 Answers

Solved using a little bit of code:

private static void EnsureDirectoryExists(string filePath) 
{ 
  FileInfo fi = new FileInfo(filePath);
  if (!fi.Directory.Exists) 
  { 
    System.IO.Directory.CreateDirectory(fi.DirectoryName); 
  } 
}

Sorry for this really newbie post... Thank you all! :-)

like image 186
Ferdinando Santacroce Avatar answered Oct 13 '22 19:10

Ferdinando Santacroce