diyoda_
diyoda_

Reputation: 5420

Changing "/" to "\" [C#]

I have already seen the other way around. But this one I can not catch. I am trying to get a part of a web resourcePath and combine it with a local path. Let me Explain a bit more.

public string GetLocalPath(string URI, string webResourcePath, string folderWatchPath) // get the folderwatcher path to work in the local folder
    {
        string changedPath = webResourcePath.Replace(URI, "");
        string localPathTemp = folderWatchPath + changedPath;
        string localPath = localPathTemp.Replace(@"/",@"\");
        return localPath;
    }

But, When I do this the result is like

C:\\Users

But what I want to have is

C:\Users 

Not "\\" but my debug shows it like C:\\Users but in the console it shows it as I expect it. I want to know the reason for that thanks..

Upvotes: 1

Views: 116

Answers (3)

Nikhil Agrawal
Nikhil Agrawal

Reputation: 48568

Because \\ is escape sequence for \

string str  = "C:\\Users";

is same as

string str  = @"C:\Users";

Later one is known as Verbatim string literal.

For combining paths in code it is better to use Path.Combine instead of manually adding "/"

Your code should be like

public string GetLocalPath(string URI, string webResourcePath, 
                           string folderWatchPath)
{
    return Path.Combine(folderWatchPath, webResourcePath.Replace(URI, ""));
}

There is no need to replace / with \ because path names in windows supports both. So C:\Users is same as C:/Users

Upvotes: 7

user743382
user743382

Reputation:

In C#, \ is special in ""-delimited strings. In order to get a literal \ in a string, you double it. \ is not special in @"" strings, so @"\" and "\\", or @"C:\Users" and "C:\\Users" mean exactly the same thing. The debugger apparently uses the second style in your case.

Upvotes: 2

Marek Dzikiewicz
Marek Dzikiewicz

Reputation: 2884

I believe that debug shows strings with escape chars, and to escape a \ in a non-verbatim (not prefixed with @) string you have to write \\.

Upvotes: 1

Related Questions