Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a file and its parent directories in one method call?

I want to create a file that is in specific directory. For example: C:\x\y\z\aTextFile.txt

For this operation, I have to create the directory to create file.

Directory.CreateDirectory(@"C:\x\y\z\");
File.Create(@"C:\x\y\z\aTextFile.txt");

But I really wonder that I can do this operation in single line of code.

Any help and idea will be greately appreciated.

like image 534
ibrahimyilmaz Avatar asked Jun 06 '12 05:06

ibrahimyilmaz


1 Answers

Simple: Add a function

void MySingleLineOfCodeFunction(string path, string filename)
{
    Directory.Createdirectory(path);
    File.Create(filename).Dispose();
}

and then use a single line of code:

MySingleLineOfCodeFunction(@"C:\x\y\z\", "a.txt");

What I am trying to say is that there is no difference between code. Some of it is written by the Microsoft guys, while other by us, normal people. But the computers don't make a difference. :)

like image 142
Petar Ivanov Avatar answered Oct 07 '22 01:10

Petar Ivanov