Reputation: 2559
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
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
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
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
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
Reputation: 620
System.IO.Path.Combine(Server.MapPath("~"), "Folder1\\Folder2\\etc")
You can read about MapPath here
Upvotes: 2
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