获取应用程序目录的完整路径

4

我有一个使用ASP.NET和C#的网站。

我想做类似于这样的事情:

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

但我不想每次都手动输入完整的路径,因为它会因计算机而异。
有什么办法可以用C#获取完整的路径?(这是应用程序当前保存的位置)

8个回答

9

2

获取应用程序路径

string appPath = HttpContext.Current.Request.ApplicationPath;

将虚拟应用程序路径转换为物理路径
string physicalPath = HttpContext.Current.Request.MapPath(appPath);

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

您可以在这里了解有关MapPath的信息。


1
AppDomain.CurrentDomain.BaseDirectory

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

如果我理解你的问题,你想将它保存在你的 ASP.NET 应用程序所在的文件夹中

否则 VMATM 的答案是完美的


1

你可以使用

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

0
我更喜欢这样解决:
string strPath = string.Format("{0}\\{1}.{2}", HttpContext.Current.Server.MapPath("~\\Images"), imageName, ".png");
bitmap.Save(strPath);

我喜欢这种方法的原因是: A)使用调试器逐步查看strPath非常容易,更容易理解发生了什么并修复它,如果不符合预期。 B)使用“+”连接字符串是一种不好的习惯。它不够可读,并且每次连接字符串时都会重新分配内存...这意味着性能较低。您应该使用string.Format或StringBuilder。

0
为了获取应用程序根目录的路径,如果您在aspx页面中,可以使用以下代码:
Server.MapPath("~/");

但如果你在另一个不继承自Page的类中,你可以使用:

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

然后使用路径组合来获取特定文件的路径

Path.Combine(root, pathFromRootToFile);

0

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接