【问题标题】:Why is this invalid file path with // working? [duplicate]为什么这个带有 // 的无效文件路径有效? [复制]
【发布时间】:2016-02-17 19:46:33
【问题描述】:

我在某个Class1中有这个功能:

    public void function1(String path){
  this.excel = new Application();
  this.wbooks = excel.Workbooks;
  this.wb = wbooks.Open(path);
  String rootPath = wb.Path+"//..//..//";
  String nPath = String.Format("{0}//Loads//{1}//{2}",rootPath,name1,name2);
  String outputDir = String.Format("{0}//Input//{1}//{2}", rootPath, name1, name2);
  String erroDir = String.Format("{0}//Erro//{1}//{2}", rootPath, name1, name2);
  for(int i = 0; i < size; i++){
     String[] array2 = File.ReadAllLines(String.Format("{0}//{1}_{2}.txt", nPath, name1, i.ToString()));
     //code
     Directory.CreateDirectory(erroDir);
     File.WriteAllLines(String.Format("{0}//erro_{1}_{2}.txt", erroDir, name1, i.ToString()), array);
     Directory.CreateDirectory(outputDir);
     File.WriteAllLines(String.Format("{0}//output_{1}.txt", outputDir, name2), array);
  }
}

这个函数来自一个类,在主函数中被这样调用:

String path = "C:\\Users\\myUsername\\Desktop\\myFolder\\";
Class1 temp = new Class1();
temp.function1(path);

为什么在函数中创建的路径有效?不应该将路径设置为“\\”而不是“//”。

【问题讨论】:

    标签: c# string path directory


    【解决方案1】:

    为什么在函数中创建的路径有效?不应该将路径设置为“\”而不是“//”。

    是的,他们应该这样做。但是 Windows 是“智能的”。它会尝试确定您实际要询问的内容,在这种情况下,如果文件路径以 C: 开头,例如,它“知道”它是本地文件路径,因此它会尝试将其解释为这样。

    请注意,并非所有程序都那么聪明。例如,一些 .NET 构建工具(不是 C# 本身)因处理此类文件路径的一些错误而闻名。

    【讨论】:

    • 我觉得这很奇怪,因为当我在另一个程序中(但在主函数中,而不是在类函数中)做类似的事情时,它不起作用,甚至 "\\..\\"工作,我不得不使用 Directory.GetParent.toString();
    猜你喜欢
    • 2018-01-06
    • 1970-01-01
    • 2013-11-17
    • 2019-09-18
    • 1970-01-01
    • 2017-04-20
    • 1970-01-01
    • 1970-01-01
    • 2021-01-06
    相关资源
    最近更新 更多