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 hardcode the path to it, as it can change. I just know its relative path, but not its physical path.

+3
source share
3 answers

For regular applications, Path.GetFullPath(path)this will return. If this is the web, then MapPaththis is what you want (e.g. Server.MapPath("~/foo/bar")).

Re comments; try it HttpContext.Current.Server.MapPath(...); in the absence HttpServerUtility(comments), try VirtualPathUtility.ToAbsolute.

+9
source

If you are looking for an absolute file path, you want System.IO.Path.GetFullPath :

.

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

-, Path .

+5

, ...

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

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

In a WinForms or Console application, if the file refers to an executable file, you can try to use System.Environment.CurrentDirectory as in

string fullPath = System.IO.Path.Combine(System.Environment.CurrentDirectory, "SomeAppRelativeDirectory/SomeFile.ext");
+3
source

Source: https://habr.com/ru/post/1721756/


All Articles