Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get path of directoryinfo object

Writing some code in C#, I was wondering if there was a way to get the correct path of a directoryinfo object?

Currently I have, for example, a directory such as:

DirectoryInfo dirInfo = new DirectoryInfo(pathToDirectory);

The issue is that if I want to get the path of that specific dirInfo object, it always returns the debug path (bin folder). If the original dirInfo object is referencing a directory in the D:\testDirectory path, then I want a way to get that path again somewhere else in the code instead of getting \bin\debug\testDirectory

Is there any way to do this?

Currently I am trying to get the path of dirInfo using Path:

Console.WriteLine("Path: " + Path.GetFullPath(dirInfo.ToString()));
like image 757
Giardino Avatar asked Nov 19 '13 17:11

Giardino


2 Answers

Try this.

string pathToDirctory = "D:\\testDirectory";
DirectoryInfo dirInfo = new DirectoryInfo(pathToDirctory);
string path = dirInfo.FullName;
Console.WriteLine(path);
like image 53
Muhammad Umar Avatar answered Sep 23 '22 03:09

Muhammad Umar


A DirectoryInfo represents a particular directory. When you create it, what directory it represents is dependent on the path you give it. If you give it an absolute path like c:\foo\bar\baz\bat, that's the directory you get. If, on the other hand, you give it a relative path, like foo\bar\baz\bat, the path is relative to the process' current working directory. By default, that is inherited from the process that spawned the current process. Visual Studio starts a debug session and sets the CWD of the process being debugged to its bin directory. So if you create a DirectoryInfo and give it a path like testDirectory, you will get a DirectoryInfo about [project-root]\bin\Debug\testDirectory.

If you want an absolute path, you'll have to specify that absolute path. There aren't any shortcuts.

like image 42
Nicholas Carey Avatar answered Sep 25 '22 03:09

Nicholas Carey