Let's say I need to create a new file whose path is ".\a\bb\file.txt". The folder a and bb may not exist. How can I create this file in C# in which folder a and bb are automatically created if not exist?
With your document open, click File > Save As. Under Save As, select where you want to create your new folder. You might need to click Browse or Computer, and navigate to the location for your new folder.
To do so, type cd followed by the path to the directory you want to create a file in and press Enter.. For example, you could type cd /home/username/Documents to navigate to your Documents folder. Alternatively, you can type cd / to navigate to the Root directory, or type cd ~ to navigate to your Home/User directory.
A path is either relative or absolute. An absolute path always contains the root element and the complete directory list required to locate the file. For example, /home/sally/statusReport is an absolute path. All of the information needed to locate the file is contained in the path string.
This will create the file along with the folders a and bb if they do not exist
FileInfo fi = new FileInfo(@".\a\bb\file.txt");
DirectoryInfo di = new DirectoryInfo(@".\a\bb");
if(!di.Exists)
{
di.Create();
}
if (!fi.Exists)
{
fi.Create().Dispose();
}
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