Click here to Skip to main content
15,881,380 members
Please Sign up or sign in to vote.
1.00/5 (2 votes)
See more:
Hi Friends
I want o define a string for example
string path="d:\\first\text.txt";
i want to create the folder(if it does not exist) and then create the file.
thank you.
Posted

1 solution

You would need to do something along these lines

C#
using System.IO;

string pathToFile = @"c:\temp\directorythatdoesntexist\file.txt";
if (!Directory.Exists(Path.GetDirectoryName(pathToFile)))
{
     Directory.CreateDirectory(Path.GetDirectoryName(pathToFile));
}

File.Create(pathToFile);
 
Share this answer
 
Comments
Ron Beyer 9-May-13 21:27pm    
The "if" statement is unnecessary in this case, Directory.CreateDirectory does nothing if the directory already exists so calling it won't have any adverse effects (like overwriting an existing directory or anything like that).
David_Wimbley 10-May-13 10:01am    
As the OP question was so basic, I just wanted to include it in case there was an specific code that needed to happen if the directory didn't exist the first time through. But yes, CreateDirectory won't explode if you call it over and over.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900