Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/320.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/.net/25.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 使用Path.Combine导航目录_C#_.net_System.io.directory - Fatal编程技术网

C# 使用Path.Combine导航目录

C# 使用Path.Combine导航目录,c#,.net,system.io.directory,C#,.net,System.io.directory,我正试图进入一些目录,然后进入输入文件夹 我试过这个 var path = Path.Combine(Directory.GetCurrentDirectory(), @"..\\..\\..\\Input\\" + filename); 但路径的价值最终是 C:\\Users\user1\\Desktop\\ToSend\\test\\reverser\\Reverser\\bin\\Debug\\..\\\\..\\\\..\\\\Input\\\\limerick.txt 有什么想法吗

我正试图进入一些目录,然后进入输入文件夹

我试过这个

var path = Path.Combine(Directory.GetCurrentDirectory(), @"..\\..\\..\\Input\\" + filename);
但路径的价值最终是

C:\\Users\user1\\Desktop\\ToSend\\test\\reverser\\Reverser\\bin\\Debug\\..\\\\..\\\\..\\\\Input\\\\limerick.txt

有什么想法吗?

您可以使用该属性。

首先,在字符串中使用@时,不需要转义\字符,因此仅使用单\斜杠可以避免结果中的双转义斜杠


关于路径问题:这取决于你想做什么。如果结果字符串用于使用
System.IO.file.*
执行一些文件操作,或使用
StreamReader
/
StreamWriter
写入/读取文件,则操作本身将在检测
\\\\
时负责遍历目录,因此无需担心

您需要获得绝对路径,而不是相对路径。因此,必须使用GetFullPath()而不是Combine()


假设您知道要从路径中删除多少层,请选中:

public string DirectoryGOUp(string path, int levelCount) {
    if(string.IsNullOrEmpty(path) || levelCount < 1)
        return path;

    string upperLevel = System.IO.Path.GetDirectoryName(path);

    if(--levelCount > 0)
        return DirectoryGOUp(upperLevel, levelCount);

    return upperLevel;
}
公共字符串目录(字符串路径,int-levelCount){ if(string.IsNullOrEmpty(path)| | levelCount<1) 返回路径; 字符串upperLevel=System.IO.Path.GetDirectoryName(路径); 如果(--levelCount>0) 返回目录goup(上级,levelCount); 返回上层; } 然后称之为:

var newPath=DirectoryGOUp(Directory.GetCurrentDirectory(),3); newPath=Path.Combine(newPath,@“Input\”+文件名)


要扩展lamloumi的答案并清理代码:

var path = Path.GetFullPath(Path.Combine(Directory.GetCurrentDirectory(), @"..\..\..\Input", filename));

应生成文件的绝对路径。

可能的重复项您要删除双\n字符还是\\。。路径?这与您的实际问题无关,但由于您在字符串前面加了
@
,因此应该使用
\
,而不是
\