Reputation: 19546
Suppose I have a folder called test
.
Now I pass that folder into a program and it will output a file called test.xyz
in the same directory that contains the target folder.
The general logic I'm using is something like
string outDir = Path.GetDirectoryName(path);
string outName = Path.GetFileName(path).TrimEnd("\\".ToCharArray()) + ".xyz";
string outFile = Path.Combine(outDir, outName);
Which works, but it seems kind of excessive to perform so many operations just to build my new filename.
1: Can I reduce the number of Path calls to achieve my result?
2: Can I do something about the second line to avoid trimming and also avoid using that add operation?
Upvotes: 1
Views: 1513
Reputation: 8192
You could use a FileInfo for that!
string path = @"C:\Windows\System32\";
FileInfo fi = new FileInfo(path);
string outFile = fi.DirectoryName + ".xyz";
works like a charm. even with trailing slash in the directory string
Upvotes: 0
Reputation: 27363
This seems to work in my quick tests:
string outFile = Path.GetFullPath(path) + ".xyz";
Although I just realized your path
may include a trailing slash already. If you can't change it to avoid that, you'll still have to include the .TrimEnd()
call.
In my test, I'm using var path = @"C:\Windows\System32";
.
Upvotes: 2