I was wondering if someone could give me a quick hand with this. I have a text box that a user types a directory location in. Obviously the directory path includes at least one "\" character and could contain many more.

Because the slash is the escape character and I want to use the path later on in the code, I need to replace the single "\" with "\\"

Here's what I did, and what the Immediate window reports:

string host = this.HostAddress.Text.Replace(@"\", @"\\");

Immediate reports host as:
"C:\\\\Program Files (x86)"
When it should report it as:
"C:\\Program Files (x86)"
the original text was:
"C:\Program Files (x86)"

Any thoughts?

string host = this.HostAddress.Text.Replace(@"\", @"\\");

Immediate reports host as:
"C:\\\\Program Files (x86)"
When it should report it as:
"C:\\Program Files (x86)"
the original text was:
"C:\Program Files (x86)"

Any thoughts?

Your call to Replace is correct, as you can demonstrate by running the following tests (the third one is supposed to be incorrect):

using System;

class Program
{
    public static void Main(string[] args)
    {
        // No @, double \
        WriteReplacement("C:\\Program Files (x86)");
        
        // With @, single \
        WriteReplacement(@"C:\Program Files (x86)");

        // With @, double \
        WriteReplacement(@"C:\\Program Files (x86)");
        
        Console.ReadKey(true);
    }
    
    private static void WriteReplacement(string text)
    {
        Console.WriteLine(
            "\"{0}\" --> \"{1}\"",
            text,
            text.Replace(@"\", @"\\"));
    }
}

...so I imagine there's something going on with the text in HostAddress .

I have to ask, though--why do you need to escape the slash in the first place? You only have to escape them when you're writing string literals in code. If you're getting typed input from the user, HostAddress.Text will be the correct path string, and doubling them up will confuse the standard IO classes.

I have to ask, though--why do you need to escape the slash in the first place? You only have to escape them when you're writing string literals in code. If you're getting typed input from the user, HostAddress.Text will be the correct path string, and doubling them up will confuse the standard IO classes.

You know what? Your right.... I don't even need to escape them! I was working on using it in a connection string and for some reason I had it stuck in my head that I had to escape them...nevermind :)

Thanks!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.