tags:

views:

146

answers:

3
+1  Q: 

Physical File Path

What is the best way to get the physical path to a file in C#?

UPDATE:

I have a file name but I don't want to hard code the path to it since it may change. I just know its relative path but not its physical path.

+3  A: 

The question is still unclear, but I'll take a shot...

If this is in Asp.Net, you can use Server.MapPath as in

string fileLocation = Server.MapPath("~/SomeAppRelativeDirectory/SomeFile.ext");

In a WinForms or Console app, if the file is relative to the executable, you can try to use System.Environment.CurrentDirectory as in

string fullPath = System.IO.Path.Combine(System.Environment.CurrentDirectory, "SomeAppRelativeDirectory/SomeFile.ext");
David Stratton
What assembly is that part of?
LB
Both are in the standard class libraries.. The first in System.Web and the next in System.IO.
David Stratton
I guess not available in .NET 2.0
LB
@LB; both MapPath and most of the various Path methods go back to 1.1
Marc Gravell
+5  A: 

If you're looking for a a file's absolute path, you want System.IO.Path.GetFullPath:

Returns the absolute path for the specified path string.

string path = "hello.txt";
Console.WriteLine(Path.GetFullPath(path));

In my opinion, the Path class is incredibly useful and woefully underused.

Michael Petrotta
+5  A: 

For regular apps, Path.GetFullPath(path) will return this. If this is web, then MapPath is what you want (for example, Server.MapPath("~/foo/bar")).

Re comments; try HttpContext.Current.Server.MapPath(...); in the absense of HttpServerUtility (comments), then try VirtualPathUtility.ToAbsolute.

Marc Gravell
I'm unable to use MapPath since the constructor to HttpServerUtility is internal :(
LB