2

I am trying to go up a few directories and then go in to the input folder...

I have tried this

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

but the value of path ends up being..

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

Any ideas?

Ayo Adesina
  • 2,231
  • 3
  • 37
  • 71
  • possible duplicate of [Path.Combine absolute with relative path strings](http://stackoverflow.com/questions/670566/path-combine-absolute-with-relative-path-strings) – Eugene Podskal Aug 20 '14 at 07:26
  • do you want to get rid of the double \ characters or the \\.. paths? – default Aug 20 '14 at 07:35
  • 1
    This is tangential to your actual issue, but since you are preceding the string literal with `@`, you should be using `\ `, not `\\ `. – JLRishe Aug 20 '14 at 07:44

5 Answers5

2

You need to get the absolute not a relative path . So you must use GetFullPath() instead of Combine().

Check this

Lamloumi Afif
  • 8,941
  • 26
  • 98
  • 191
0

You can use the DirectoryInfo.Parent Property.

JLRishe
  • 99,490
  • 19
  • 131
  • 169
Davut Özcan
  • 109
  • 13
0

First of all, when using @ with Strings there is no need to escape \ characters, so by just using single \ slashes you can avoid the double-escaped slashes in the result.

Concerning the path question: It depends on what you want to do. If the result string is used to do some file operations using System.IO.File.* or to write/read from a file using StreamReader/StreamWriter, the operation itself will take care of walking up the directories when detecting \..\, so no need to worry!

andreask
  • 4,248
  • 1
  • 20
  • 25
0

Assuming you know how many levels you want to remove from your path:

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;
}

And then call it:

var newPath = DirectoryGOUp(Directory.GetCurrentDirectory(),3); newPath = Path.Combine(newPath, @"Input\"+filename);

Adam Bilinski
  • 1,188
  • 1
  • 18
  • 28
0

To expand on lamloumi's answer and cleanup the code:

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

should produce the absolute path to your file.

ths
  • 2,858
  • 1
  • 16
  • 21