Reputation: 2395
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?
Upvotes: 2
Views: 3633
Reputation: 2942
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.
Upvotes: 1
Reputation: 1198
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);
Upvotes: 0
Reputation: 9081
You need to get the absolute not a relative path . So you must use GetFullPath() instead of Combine().
Check this
Upvotes: 2
Reputation: 4298
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!
Upvotes: 0