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

Simple: Add a function

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

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. :)


Unfortunately no there is no single line of code to do what you want.

Why? Because even if we do so by some Microsoft inbuilt function, internally it will be calling two methods. One for Directory creation and other for file creation.

However you can reduce your lines of code by making them into a method and call it in a single line as Petar Ivanov said

OR

You can create a static extension method. This way you can use it at other places without creating instance. (Reduced your one line where instance is created).


As far I know, there is no File creation method that create the directory at the same time in the .NET framework.

If the pattern "Directory check/creation, then file creation" is repeated a lot in your code, you have to implement it in a method.