更换'\';与'/';在字符串C#WinForm应用程序中

更换'\';与'/';在字符串C#WinForm应用程序中,c#,winforms,string,C#,Winforms,String,任何人都可以建议一种用斜杠“/”替换字符串中反斜杠“\”的方法。基本上,字符串是一条路径。我尝试过使用string的Replace()方法,但它不起作用 谢谢您需要捕获替换的结果(字符串是不可变的),并确保对\使用字符转义: string path = Directory.GetCurrentDirectory(); path = path.Replace("\\", "/"); 获取信息;大多数内置方法都可以接受,并且假设您在Windows上,\将更常见。如果需要uri,请使用uri: st

任何人都可以建议一种用斜杠“/”替换字符串中反斜杠“\”的方法。基本上,字符串是一条路径。我尝试过使用string的Replace()方法,但它不起作用


谢谢

您需要捕获替换的结果(字符串是不可变的),并确保对
\
使用字符转义:

string path = Directory.GetCurrentDirectory();
path = path.Replace("\\", "/");
获取信息;大多数内置方法都可以接受,并且假设您在Windows上,
\
将更常见。如果需要uri,请使用
uri

string path = Directory.GetCurrentDirectory();
Uri uri = new Uri(path); // displays as "file:///C:/Users/mgravell/AppData/Local/Temporary Projects/ConsoleApplication1/bin/Debug"
string abs = uri.AbsolutePath; // "C:/Users/mgravell/AppData/Local/Temporary%20Projects/ConsoleApplication1/bin/Debug"

这只是一点关系,但当我看到使用\字符时,我喜欢提到它;以防有人不知道

注意,C#有一个语法转义字符,@符号。您可以使用它来转义保留字,但更常见的是,您将使用它来转义字符串文字转义序列

例如,如果要在文本中使用\字符,并且不想用另一个\转义,则可以在文本前面加@。因此,上面的代码可以这样编写:

path = path.Replace(@"\", "/") 路径=路径。替换(@“\”,“/”) 我发现它在处理文件路径时非常有用:

var path = "C:\\Documents and Settings\\My Documents\\SomeFile.txt"; var path=“C:\\Documents and Settings\\My Documents\\SomeFile.txt”; 可以写为:

var path = @"C:\Documents and Settings\My Documents\SomeFile.txt"; var path=@“C:\Documents and Settings\My Documents\SomeFile.txt”;
它有助于提高可读性。

您需要sitePath=sitePath.Replace(“\\”,“/”;as.Replace创建一个新实例我认为您需要执行以下操作:sitePath=sitePath.Replace(“\\”,“/”;这就是Marc所说的字符串是不可变的,调用函数不会改变字符串的值,函数会返回一个新字符串。非常感谢。我忽略了字符串是不可变的这一点。非常感谢。你已经回答了我所有的问题。