代码之家  ›  专栏  ›  技术社区  ›  Megidd

获取带有scape字符的临时路径

  •  0
  • Megidd  · 技术社区  · 2 年前

    我如何从中获取路径 Path.GetTempPath() 格式如下:

    C:\\Users\\m3\\AppData\\Local\\Temp\\
    

    不是这样的:

    C:\Users\m3\AppData\Local\Temp\
    

    我的意思是我想要它 \ 景观人物。有自动的方法吗?或者我需要补充 \ 角色本身?

    我需要写入文件的路径和 \ 字符必须是 \\ .

    2 回复  |  直到 2 年前
        1
  •  2
  •   Steve    2 年前

    将路径中的分隔符字符加倍的简单方法如下

    var psep = Path.DirectorySeparatorChar;
    var p = Path.GetTempPath().Replace($"{psep}", $"{psep}{psep}");
    Console.WriteLine(p);  
    
        2
  •  1
  •   Miles    2 年前

    使用字符串。替换:

    string tempPath = Path.GetTempPath();
    string formattedPath = tempPath.Replace(@"\", @"\\");
    

    或路径。目录分隔符字符:

    string tempPath = Path.GetTempPath();
    string formattedPath = tempPath.Replace(Path.DirectorySeparatorChar.ToString(), Path.DirectorySeparatorChar + @"\");
    

    这两种方法都运行良好,在vscode多语言笔记本C#中进行了测试:

    using System.IO; 
    string tempPath = Path.GetTempPath(); 
    string formattedPath = tempPath.Replace(@"\", @"\\"); Console.WriteLine(formattedPath); 
    

    退货: C:\\Users\\name\\AppData\\Local\\Temp\\

    using System.IO;
    string tempPath = Path.GetTempPath(); string formattedPath = tempPath.Replace(Path.DirectorySeparatorChar.ToString(), Path.DirectorySeparatorChar + @"\"); 
    Console.WriteLine(formattedPath); 
    

    退货: C: \\Users\\name\\AppData\\Local\\Temp\\