Environment with string replace ....

  • Thread starter Thread starter Gabriel
  • Start date Start date
G

Gabriel

Hello,

I do this :

s = Environment.CurrentDirectory;
s = s.Replace("\\", @"\");
Environment.CurrentDirectiry return a path like this C:\\....\\....\\.....
I'd like replace the \\ by \, but the code I use not work. Any idea ?

Best Regards,
 
You forgot @ at first string.
s.Replace(@"\\", @"\");

Hello Alex,

It's strange that. In the debugger I see \\ but when I display the path in
the application caption I see \

Thanks,
 
Gabriel,

Do Console.WriteLine(s) and it prints correctly. Internally \\ is the
code for backslash... the first backslash gets special handling. Its
used for \n is newline, \t is tab, and \\ is backslash.

-James
 
The back slash is a special character to the C# compiler. So, when you want
to use it in a string, you must place an escape character in front of it.
The escape character is also a back slash. (alternatively, you can place the
'@' character in front of a string to indicate to the compiler that the
following is a literal string, with no special characters in it.

Consequently the compiler treats or sees
"\\"
and
@"\"
as the exact same string.

So your original replace operation , s = s.Replace("\\", @"\"); , replaces
a single back slash with a single back slash. This is a nonsensical
operation.

If you want to replace two back slashes with a single back slash, either of
these should work:
s = s.Replace("\\\\", "\\");
or
s = s.Replace(@"\\", @"\");

Note that this "escape character" stuff is all for the compiler. So the
comiler will, for example, translate "\\" to be "\" in the output assembly.
This is why you see "\\" in Visual Studio, when your application shows "\"

-HTH

-S
 
It's strange that. In the debugger I see \\ but when I display the path in
the application caption I see \

What you're seeing in the debugger is the string literal you'd have to
type in to get the actual string. It catches lots of people out. The
*real* string only has a single backslash.

Jon
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Back
Top