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.
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.
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");
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.
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
.