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

File.Copy()或Directory.CreateDirectory()方法的路径变量中有多余的斜杠

  •  1
  • JohnB  · 技术社区  · 15 年前

    System.IO 方法,并“意外地”放置额外的斜杠( \

    例子:

    Directory.CreateDirectory(@"C:\Users\Public\Documents\\test");
    File.Copy(@"C:\Users\Public\\Documents\test.txt", @"C:\Users\\Public\Documents\test\test.txt", true);
    

    4 回复  |  直到 15 年前
        1
  •  1
  •   Community Mohan Dere    9 年前

    Windows对此很有弹性,还没有发现问题。

    看一看 the snippet 在这条线上。请注意_ACP_INCLUDE环境变量的值。您必须向右滚动才能看到:

    C:\Program Files\Microsoft SDKs\Windows\v6.0A\\include;

        2
  •  1
  •   Hogan    15 年前

    Windows似乎并不介意,但为什么不编写优雅的代码呢?

        3
  •  1
  •   Evan Mulawski    15 年前

    我确信Windows在使用路径结构之前会将其“规范化”。但是,为了安全起见,最好使用以下方法组合路径:

    Path.Combine(string1, string2);
    

        4
  •  0
  •   Benjamin    15 年前

    CreateFileW(L"D:\\1\\test.txt", GENERIC_READ, 0, 0, CREATE_NEW, 0, 0);
    // A file has been created.
    
    CreateFileW(L"D:\\1\\test.txt", GENERIC_READ, 0, 0, OPEN_EXISTING, 0, 0);
    // Of course, the file will be opened well.
    
    CreateFileW(L"D:\\1\\\\test.txt", GENERIC_READ, 0, 0, OPEN_EXISTING, 0, 0);
    // It works well too. Windows subsystem does canonicalize that.
    
    CreateFileW(L"\\\\?\\D:\\1\\\\test.txt", GENERIC_READ, 0, 0, OPEN_EXISTING, 0, 0);
    // '\\?\' prefix tell Windows "Don't touch my path, just send it to filesystem"
    // So it will be failed.
    

    http://msdn.microsoft.com/en-us/library/aa365247(VS.85).aspx#maxpath
    我不知道.NET如何包装这个api。我想汉斯·帕桑特可能很清楚这一点。:)

    推荐文章