C#: Creating a new FileInfo in a directory that yo

2020-06-30 11:42发布

问题:

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.

回答1:

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.



回答2:

Why don't you use:

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

or

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


回答3:

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));
    }