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 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");
精彩评论