Svish
Svish

Reputation: 157991

C#: Creating a new FileInfo in a directory that you have the DirectoryInfo of

I was just wondering when you have for example:

var dir = new DirectoryInfo(@"C:\Temp");

Is there an easier/clearer way to add a new file to that directory than this?

var file = new FileInfo(Path.Combine(dir.FullName, "file.ext"));

I'm thinking I can probably just make an extension method or something, but curious if something already exists that can't see here... I mean the DirectoryInfo does have GetFiles() method for example.

Upvotes: 22

Views: 33055

Answers (3)

Fredrik Mörk
Fredrik Mörk

Reputation: 158309

What is it that you want to do? The title says "Creating a new file". A FileInfo object is not a file; it's an object holding information about a file (that may or may not exist). If you actually want to create the file, there are a number of ways of doing so. One of the simplest ways would be this:

File.WriteAllText(Path.Combine(dir.FullName, "file.ext"), "some text");

If you want to create the file based on the FileInfo object instead, you can use the following approach:

var dir = new DirectoryInfo(@"C:\Temp");
var file = new FileInfo(Path.Combine(dir.FullName, "file.ext"));
if (!file.Exists) // you may not want to overwrite existing files
{
    using (Stream stream = file.OpenWrite())
    using (StreamWriter writer = new StreamWriter(stream))
    {
        writer.Write("some text");
    }
}

As a side note: it is dir.FullName, not dir.FullPath.

Upvotes: 21

Jay Bazuzi
Jay Bazuzi

Reputation: 46496

While there does exist Directorynfo.GetFiles() methods, they only return files that actually exist on disk. Path.Combine is about hypothetical paths.

Try these extension methods:

    public static FileInfo CombineWithFileName(this DirectoryInfo directoryInfo, string fileName)
    {
        return new FileInfo(Path.Combine(directoryInfo.Name, fileName));
    }

    public static DirectoryInfo CombineWithDirectoryName(this DirectoryInfo directoryInfo, string directoryName)
    {
        return new DirectoryInfo(Path.Combine(directoryInfo.Name, directoryName));
    }

Upvotes: 1

Bhaskar
Bhaskar

Reputation: 10681

Why don't you use:

File.Create(@"C:\Temp\file.ext");

or

var dir = new DirectoryInfo(@"C:\Temp");
File.Create(dir.FullName + "\\file.ext");

Upvotes: 2

Related Questions