Paul Michaels
Paul Michaels

Reputation: 16705

Using DirectoryInfo in C#

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

Upvotes: 0

Views: 1119

Answers (2)

brickner
brickner

Reputation: 6585

@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");

Upvotes: 2

Hans Olsson
Hans Olsson

Reputation: 55059

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

As you say, you already have the path.

Upvotes: 5

Related Questions