Trying to convert string "TextText" to "Text

J

Joebloggs

Hi

I am trying to do an ldap lookup. I can pick up the domain name in the
standard format DOMAIN\USERNAME. The problem is the company I work for
expects the query in the format DOMAIN:USERNAME.
I tried to do a simple string replace to replace \ to : but it turns
out the only string you can't replace in c# is \ as it gives the
error "Invalid Escape Sequence" - using "\\" or @"\" doesnt work
either

// doesnt work
string result = Regex.Replace(string.Format("{0}", b), "\", ":");


Next step I tried was to convert the string to unicode and replace the
unicode \ with a unicode :

This works in terms of outputting to a label but does anyone know how
to convert a unicode sequence back to string values

Code:
string u1 = username.Text;

UnicodeEncoding unicode = new UnicodeEncoding();
Byte[] encodedBytes = unicode.GetBytes(u1);
foreach (Byte b in encodedBytes)
{
string result = Regex.Replace(string.Format("{0}", b), "92", "58");
// as output to a label to test result
l1.Text += string.Format("{0}", result);
}

This code will output a unicode sequence to a label but its not very
useful. What I need to do is encode the unicode back to string and
pass that to my ldap code to perform the query (which works fine if I
hard code it).

What I tried to do was to create another Byte[] called decodedBytes
and add each parsed token from the first Byte[] and decode this when
complete.
Code:
String decodedString = unicode.GetString(decodedBytes);

Does anyone know an alternative way to convert \ to : or does anyone
know how to convert a unicode sequence back to string values.

Thanks
 
S

Steve Willcock

Both these string.Replace method overloads work:

string loginName = @"DOMAIN\USERNAME";
Console.WriteLine(loginName.Replace("\\", ":"));

Console.WriteLine(loginName.Replace('\\', ':'));
 
J

Joebloggs

Thanks Steve

I just discovered that myself!
One of those beginer errors!




string u1 = username.Text;
u1 = u1.Replace('\\', ':');
 

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

Top