1

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?

1
  • Please let us know whether an answer was helpful. Commented Jun 10, 2012 at 21:01

2 Answers 2

2

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

Sign up to request clarification or add additional context in comments.

2 Comments

in addition to this, you can use Path.Combine to avoid trimming
@sblom, use @"C:\windows\system32" as test path seemed not safe. lol
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.