Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations John Tel on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

String.replace method

Status
Not open for further replies.

ace333

Programmer
Jul 12, 2005
105
CH
I want to use the .replace() method in the string object to change the \ into a \\ so that instead of hard coding the file path below I can do it dynamically. However when I try the following in c# I get an error
String.Replace("\","\\") because the \ has to be escaped. But if I put \\ it wont find the \ in the string. Bit of a puzzle



File c:\temp\e.xml


XmlTextReader xtr = new XmlTextReader("C:\\temp\\e.xmll);
 
If you put the @ character before the opening quotes the compiler will read the string literally and you won't have to escape anything. So you could use:

Code:
XmlTextReader xtr = new XmlTextReader(@"C:\temp\e.xmll);

Nelviticus
 
Will this work if the string is in a variable name like

mlTextReader xtr = new XmlTextReader(@variableName);
 
Not sure - I don't have VS installed on this machine. You could try it and see whether it compiles.

If not you can use @ elsewhere, i.e. String.Replace(@"\", @"\\")

Nelviticus
 
I'm a little confused. If you are hard-coding a path, you can use
Code:
XmlTextReader xtr = new XmlTextReader(@"C:\temp\e.xml");

// or

XmlTextReader xtr = new XmlTextReader("C:\\temp\\e.xml");
to escape the backslashes. If you already have a path in a variable, you shouldn't need to edit it further.

When you say you want to 'do it dynamically', where are you going to get the dynamic path from? Are you reading it from a file? Building it up from some other data? If you can be more specific about what you are trying to do, we may be able to be more helpful...
 
The previous tip helped, thanks though
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top