views:

64

answers:

2

If there a more efficient way to do the following:

DirectoryInfo di = new DirectoryInfo(@"c:\");
newFileName = Path.Combine(di.FullName, "MyFile.Txt");

I realise that it’s only two lines of code, but given that I already have the directory, it feels like I should be able to do something like:

newFileName = di.Combine(“MyFile.txt”);

EDIT:

Should have been more clear - I already have the path for another purpose, so:

DirectoryInfo di = MyFuncReturnsDir();
newFileName = Path.Combine(di.FullName, "MyFile.Txt");
+5  A: 

Why not just do newFileName = Path.Combine(@"c:\", "MyFile.Txt");?

As you say, you already have the path.

ho1
+1, was my first thought too.
OregonGhost
I've edited my post - I have the DirectoryInfo object for a reason
pm_2
@pm_2: I'm not sure that it would make things better, but you could always write `newFileName = Path.Combine(MyFuncReturnsDir().FullName, "MyFile.Txt");` if you want it on one line.
ho1
I just wanted to see if there was a more efficient way of doing it.
pm_2
+2  A: 

@ho1 is right.

You can also write an extension method (C# 3.0+):

public static class DirectoryInforExtensions
{
  public static string Combine(this DirectoryInfo directoryInfo, string fileName)
  {
    return Path.Combine(di.FullName, fileName);
  }
}

and use it by doing

newFileName = di.Combine("MyFile.txt");
brickner