【问题标题】:How can i replace both Forward(//) and backword(\) slash in a string to forward slash(/)?如何将字符串中的正斜杠(//)和反斜杠(\)替换为正斜杠(/)?
【发布时间】:2019-07-12 07:46:26
【问题描述】:

我有一个这样的字符串: D:\\文件夹\\文件夹\\文件夹/文件夹/文件夹 因为它与正向和反向斜杠混合在一起,所以目录不能 查找文件,但如果我像这样更改它 D:\folder\folder\folder\folder\folder 路径是正确的。

我已经尝试过这样做

sourceStreamId=D:\\folder\\folder\\folder/folder/folder
string appdomain = HttpRuntime.AppDomainAppPath;
string destinationFile=System.IO.Path.Combine(appdomain,sourceStreamId).Replace("\\", @"\");

但这导致了这样的字符串 D:\\文件夹\\文件夹\\文件夹/文件夹/文件夹

任何人都可以为此提供解决方法

我来过这里:How to replace the double backslash with a single backslash 但是那个字符串只有双反斜杠我有正反斜杠

【问题讨论】:

  • "\\" 和 @"\" 是同一个东西。
  • 但是当我使用\\ 作为路径时找不到文件?使用\ 是正确的!!!
  • 你正在替换同样的东西。 "\\" 是 "\" 和 @"\" 是 "\"。
  • 要解决这个问题,您需要像这样将@ 添加到"\\":.Replace(@"\\", @"\");

标签: c# asp.net string


【解决方案1】:

尝试如下:-

string destinationFile=System.IO.Path.Combine(appdomain,sourceStreamId).Replace(@"\\", @"\");

例如:-

string path = "C:\Hg\temp/test\\LogFile.txt";
path = path.Replace(@"\\", @"\"); 
string output = path.Replace(@"/", @"\"); 

输出>>> C:\Hg\temp\test\LogFile.txt

【讨论】:

    【解决方案2】:

    要替换机器人,只需调用Replace 两次:

    string destinationFile = System.IO.Path.Combine(appdomain,sourceStreamId)
                                           .Replace(@"\\", @"\")
                                           .Replace("/", @"\");
    

    参考:DotNetFiddle Example

    【讨论】:

      【解决方案3】:

      您可以利用 Path 为您修复它:

      var ourceStreamId = "D:\\folder\\folder\\folder/folder/folder";
      
      var path = Path.GetFullPath(ourceStreamId);
      Console.WriteLine(path);
      //output: D:\folder\folder\folder\folder\folder
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-02-27
        • 2021-05-29
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-01-27
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多