views:

1541

answers:

3

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.

A: 

The code in your question looks about right to me (marked as wiki as I'm not really adding value here...)

Marc Gravell
+1  A: 

Why dont you use:

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

OR

var dir = new DirectoryInfo(@"C:\Temp");
File.Create(dir.FullName + "\\file.ext");
Bhaskar
IMO, the OP is correct in using Path.Combine rather than +
Marc Gravell
Because I have the DirectoryInfo and a file name. Not both together.
Svish
+2  A: 

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.FullPath, "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.

Fredrik Mörk
oh, good call. FullPath was protected field. FullName is the property. Just scanned the MSDN member page a bit too fast :)
Svish