开发者

Using DirectoryInfo in C#

开发者 https://www.devze.com 2023-01-03 16:21 出处:网络
If there a more efficient way to do the following: DirectoryInfo di = new DirectoryInfo(@\"c:\\\"); newFileName = Path.Combine(di.FullName, \"MyFile.Txt\");

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 lik开发者_StackOverflow中文版e:

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


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

As you say, you already have the path.


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

精彩评论

暂无评论...
验证码 换一张
取 消