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

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

For this operation, I need to create a directory to create the file.

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

But I'm really curious that I can do this operation in one line of code.

Any help and idea would be greatly appreciated.

+7
source share
6 answers

As far as I know, there is no way to create a file that simultaneously creates a directory in the .NET environment.

If the "Check / create a directory, then create a file" template repeats a lot in your code, you must implement it in the method.

+2
source

Simple: add function

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

and then use one line of code:

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

, , , . Microsoft, - . .:)

+2

, , , .

? , Microsoft, . .

, ,

. , . ( , ).

+2

, . , Visual Basic, . , .

CreateFile http://msdn.microsoft.com/en-us/library/windows/desktop/aa363858(v=vs.85).aspx

, CreateFile, OPEN_EXISTING dwCreationDisposition . , CreateDirectory CreateDirectoryEx

+1

@Petar_Ivanov, , , , .

    public void CreateFile(string filePath)
    {
        if (!File.Exists(filePath))
        {
            var parent = Directory.GetParent(filePath);
            Directory.CreateDirectory(parent.FullName);
            File.Create(filePath);
        }
    }

, ; File.Create , .

0

Mostly in my code blocks; I handle the existence of a folder just before creating the files.

public void CheckCreatePath(fileName)
{
    string filePath = Directory.GetParent(fileName).ToString();
    if (!Directory.Exists(filePath))
        Directory.CreateDirectory(filePath);
}

and just use

CheckCreatePath("C:\\TEMP\\TESTPath\\myFile.txt");

in your code block.

0
source

All Articles