2

In python, I take a raw string, and then pass it to os.path.normpath to make it a proper pathname. It escapes all the stuff I need escaped and I don't have to worry about it. Is there an equivalent in C#?

Here is a python snippet.

myClassProjectPath = os.path.normpath(r"C:\Users\Documents\SharpDevelop Projects\Project With Spaces\MyClass\bin\Debug")

EDIT: I am worried about slashes and spaces. Right now, I'm hardcoding the path in the code, but it will soon be a user input, so I can't control "/" vs "\"

Johan B
  • 890
  • 3
  • 23
  • 39
oob
  • 1,948
  • 3
  • 26
  • 48
  • What's the difference between a raw string and a proper path name? In c# both has \\s instead of / or \, and since .net is fully compatible with "modern" filenames both can contain spaces, etc. – TDaver Mar 13 '11 at 20:56
  • Use `/` not `\\``. So much better. I mean, I can't even get `\\`` to show up right... – alternative Mar 13 '11 at 21:03

4 Answers4

3

Also check out:

string normalizedPath = Path.GetDirectoryName(path);

This will fix / vs \ as well.

BrokenGlass
  • 158,293
  • 28
  • 286
  • 335
  • This works when I use the @ to make path a string literal as suggested below. Thanks! – oob Mar 14 '11 at 01:22
2

You can always add an @ in front to create a verbatim string literal.

What's the @ in front of a string in C#?

Community
  • 1
  • 1
Simen S
  • 3,210
  • 18
  • 24
2

Try to Path.Combine the path with nothing, or Path.ChangeExtension it to Path.GetExtension. Maybe one of these useless procedures (or another) normalizes.

Apart from that: The Path class doesn’t seem to contain the function.

Alternatively, you can program it yourself. From the Python doc:

Normalize a pathname. This collapses redundant separators and up-level references
so that A//B, A/B/, A/./B and A/foo/../B all become A/B.

It does not normalize the case (use normcase() for that). On Windows, it converts
forward slashes to backward slashes. It should be understood that this may change
the meaning of the path if it contains symbolic links!
flying sheep
  • 8,475
  • 5
  • 56
  • 73
1

I think you could both use

string s = s.Replace(@"\", @"\\");

and

string path = @"C:\Users\Documents\SharpDevelop Projects\Project With Spaces\MyClass\bin\Debug";

Found these answers at how to automatically escape the path.

Community
  • 1
  • 1
Johan B
  • 890
  • 3
  • 23
  • 39
  • hmmm. seems to take care of the slashes but not the spaces? I'm using SharpDevelop. When I'm debugging and I see the path variable, it cuts off after the first space. – oob Mar 13 '11 at 21:02
  • Maybe there is some other problem in your code. Could you give the problem some more context? – Simen S Mar 13 '11 at 21:08
  • hmmm. you are right. I just tried a simple "Hello World" and it does take care of spaces as well. I will look more into my specific code and post if I can't figure it out quickly. Thanks for the help! – oob Mar 13 '11 at 21:14