NullReferenceException
NullReferenceException

Reputation: 279

How to create a new path by replacing only a folder name of the path?

I tried replacing it by the code below, but I get an error, "unrecognized escape sequence".

string originalPath = @"C:\project\temp\code";
string newPath = "";

newPath = originalPath.Replace("C:\project\temp", "C:\project\files");

Upvotes: 0

Views: 59

Answers (3)

Sudhakar Tillapudi
Sudhakar Tillapudi

Reputation: 26209

In a String Declaration, if you use @ Symbol then String will be taken intact, in fact you don't need to bother about the escape sequences.

you have created OriginalPath variable with @ symbol so it will be taken as :

originalPath = "C:\project\temp\code";

Hence following both statements are valid:

1.string originalPath = @"C:\project\temp\code";
2.string originalPath = "C:\\project\\temp\\code";

Hence While Replacing the string you could use either of the way asbelow:

Solution 1:
newPath = originalPath.Replace("C:\\project\\temp","C:\\project\\files");

Solution 2:

newPath = originalPath.Replace(@"C:\project\temp", @"C:\project\files");

Upvotes: 1

user2533527
user2533527

Reputation: 256

I think you should use double '/' ,because first string is '@' and second isn't .

If it doesn't work I would suggest to find the instance of the temp using string.contains and Put \n there afterwards append the string with files .

If it doesn't work the try to use regex .

Upvotes: 1

Christopher Stevenson
Christopher Stevenson

Reputation: 2861

Every string literal with backslashes needs either doubled baskslashes, or the @ symbol for a quoted string.

The 'unrecognized escape sequence' is "\p".

Try this:

newPath = originalPath.Replace(@"C:\project\temp", @"C:\project\files");

Upvotes: 1

Related Questions