I just can't get around this. I am able to create a file with File.Create
... File.CreateText
and so on but only if the path exists. If the path doesn't exist the file won't be written and returns an error.
How can I create the path?
To create a file if not exist in Python, use the open() function. The open() is a built-in Python function that opens the file and returns it as a file object. The open() takes the file path and the mode as input and returns the file object as output.
C# StreamWriter append text This constructor initializes a new instance of the StreamWriter class for the specified file by using the default encoding and buffer size. If the file exists, it can be either overwritten or appended to. If the file does not exist, the constructor creates a new file.
To create a directory if not exist in Python, check if it already exists using the os. path. exists() method, and then you can create it using the os. makedirs() method.
Exists(path) method. It returns a boolean value indicating whether the file at the specified path exists or not. The File. Exists() method returns true if the file exists and false when the file doesn't exist or the caller does not have read access to the file.
Try
Directory.CreateDirectory(@"C:\MyApp\MySubDir\Data")
http://www.devx.com/vb2themax/Tip/18678
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 ...
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
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
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With