c# - 将“/”更改为“\” [C#]

标签 c#

我已经看到了另一种方式。但是这一点我抓不到。我正在尝试获取Web resourcePath的一部分,并将其与本地路径结合起来。
让我解释一下。

public string GetLocalPath(string URI, string webResourcePath, string folderWatchPath) // get the folderwatcher path to work in the local folder
    {
        string changedPath = webResourcePath.Replace(URI, "");
        string localPathTemp = folderWatchPath + changedPath;
        string localPath = localPathTemp.Replace(@"/",@"\");
        return localPath;
    }


但是,当我这样做时,结果就像

C:\\Users


但是我想拥有的是

C:\Users 


不是“ \\”,而是我的调试显示它像C:\\Users一样,但是在控制台中它按我的期望显示。
我想知道原因
谢谢..

最佳答案

因为\\\的转义序列

string str  = "C:\\Users";


与...相同

string str  = @"C:\Users";


后来的一个被称为Verbatim字符串文字。

为了在代码中合并路径,最好使用Path.Combine而不是手动添加"/"

您的代码应该像

public string GetLocalPath(string URI, string webResourcePath, 
                           string folderWatchPath)
{
    return Path.Combine(folderWatchPath, webResourcePath.Replace(URI, ""));
}


无需将/替换为\,因为Windows中的路径名支持这两种。因此C:\UsersC:/Users相同

关于c# - 将“/”更改为“\” [C#],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10910401/

相关文章:

c# - 无法通过一个查询使用 Include 或 ThenInclude 或 Select/Many 加载相关数据

c# - 从逻辑应用调用 Azurefunction 会抛出 "Runtime keys are stored on blob storage. This API doesn' t 支持此配置。”

c# - Do Loop,一种高效的中断方法?

c# - 删除文本框上的默认鼠标悬停/焦点效果

c# - 通过 ViewModel 验证模型

c# - 如何从 WCF 服务应用程序获取客户端地址?

javascript - 如何在 C# 中验证 Javascript 的authenticode

c# - 如何将 SignalR 与 Xamarin 结合使用

c# - 为特定的 Razor Pages 路由调用特定的过滤器?

C# 设置问题。