Ovi
Ovi

Reputation: 2559

get full path of application directory

I have a website that is using ASP.NET and C#.

I am trying to do something like this

bitmap.Save(@"C:\Documents and Settings\Berzon\Desktop\Kinor\kWebGUI\Images\" + imageName + ".png")

But I dont want to have to write that whole path, since it changes from computer to computer.
How can I get the full path with C#? (this path is were the application is currently being saved)

Upvotes: 4

Views: 7507

Answers (8)

Atzoya
Atzoya

Reputation: 1387

In order to get the path to the application root, if you are in a aspx page you can use:

Server.MapPath("~/");

But if you are in another class that doesn't inherit from Page you can use:

System.Web.HttpContext.Current.Server.MapPath("~/");

After that use path combine to get the path to the specific file

Path.Combine(root, pathFromRootToFile);

Upvotes: 0

DavidJBerman
DavidJBerman

Reputation: 955

I prefer to solve it like this:

string strPath = string.Format("{0}\\{1}.{2}", HttpContext.Current.Server.MapPath("~\\Images"), imageName, ".png");
bitmap.Save(strPath);

The reasons I prefer this approach are: A) Its very easy to step through with the debugger and see what strPath is, easier to understand what's happening and fix if its not what you expect. B) Using "+" to concatenate strings is a bad habit. It's less readable, and every time you concatenate the strings the memory is re-allocated... that means lower performance. You should instead use string.Format OR StringBuilder.

Upvotes: 0

VMAtm
VMAtm

Reputation: 28355

Use this:

bitmap.Save(System.IO.Path.Combine(Server.MapPath("~/RELATIVE PATH OF YOUR APPLICATION"), imageName + ".png"));

Or some of properties of HttpContext.Current.Request (ApplicationPath or AppDomain.CurrentDomain.BaseDirectory, for example)

Upvotes: 9

abhijit
abhijit

Reputation: 1968

AppDomain.CurrentDomain.BaseDirectory

System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory,image.png)

if i understood your question you want to save it in afolder where your asp.net application is located

else VMATM ans is perfect

Upvotes: 1

Svetlin Panayotov
Svetlin Panayotov

Reputation: 620

System.IO.Path.Combine(Server.MapPath("~"), "Folder1\\Folder2\\etc")

You can read about MapPath here

Upvotes: 2

SMK
SMK

Reputation: 2158

you can use

Server.MapPath("imageName + ".png");

Upvotes: 1

Emond
Emond

Reputation: 50672

Server.MapPath can help could help. Read this

Upvotes: 0

Bibhu
Bibhu

Reputation: 4081

Retrieve the application path

string appPath = HttpContext.Current.Request.ApplicationPath;

Convert virtual application path to a physical path

string physicalPath = HttpContext.Current.Request.MapPath(appPath);

Upvotes: 2

Related Questions