C# 访问根目录中的文件夹

C# 访问根目录中的文件夹,c#,asp.net,C#,Asp.net,您好,我正在开发一个asp.net web应用程序。我必须访问根目录下images文件夹中的一个映像。我正在我的代码隐藏文件中使用以下代码 string imageDirectory = HttpContext.Current.Server.MapPath("~/images/"); string imageUrl = imageDirectory + "/img1.bmp"; 这在我的本地机器上运行良好。我的问题是,当我将应用程序移动到生产环境时,这段代码是否有效?只要您的站点有一个应用程序

您好,我正在开发一个asp.net web应用程序。我必须访问根目录下images文件夹中的一个映像。我正在我的代码隐藏文件中使用以下代码

string imageDirectory = HttpContext.Current.Server.MapPath("~/images/");
string imageUrl = imageDirectory + "/img1.bmp";

这在我的本地机器上运行良好。我的问题是,当我将应用程序移动到生产环境时,这段代码是否有效?

只要您的站点有一个应用程序根目录/虚拟目录,这段代码就应该有效

string imageDirectory = HttpContext.Current.Server.MapPath("~/images/");
string imageUrl = imageDirectory + "/img1.bmp";
此外,您还可以将这两行组合为:

string imageDirectory = HttpContext.Current.Server.MapPath("~/images/");
string imageUrl = imageDirectory + "/img1.bmp";
string imageUrl = HttpContext.Current.Server.MapPath("~/images/img1.bmp");

只要您的站点有一个应用程序根目录/虚拟目录,它就应该存在

string imageDirectory = HttpContext.Current.Server.MapPath("~/images/");
string imageUrl = imageDirectory + "/img1.bmp";
此外,您还可以将这两行组合为:

string imageDirectory = HttpContext.Current.Server.MapPath("~/images/");
string imageUrl = imageDirectory + "/img1.bmp";
string imageUrl = HttpContext.Current.Server.MapPath("~/images/img1.bmp");

如果您正在考虑将
imageUrl
放入
标记中,那么不,它不会起作用
Server.MapPath
将以本地Windows文件/目录名的形式返回您的文件或目录,例如“C:\WebRoot\MyWebApplication”。如果您将其发送到浏览器,显然,浏览器不会拾取图像

string imageDirectory = HttpContext.Current.Server.MapPath("~/images/");
string imageUrl = imageDirectory + "/img1.bmp";
您可以做的是:

string imageDirectory = HttpContext.Current.Server.MapPath("~/images/");
string imageUrl = imageDirectory + "/img1.bmp";
string imageUrl = ResolveClientUrl("~/images/myImage.gif");

如果您正在考虑将
imageUrl
放入
标记中,那么不,它不会起作用
Server.MapPath
将以本地Windows文件/目录名的形式返回您的文件或目录,例如“C:\WebRoot\MyWebApplication”。如果您将其发送到浏览器,显然,浏览器不会拾取图像

string imageDirectory = HttpContext.Current.Server.MapPath("~/images/");
string imageUrl = imageDirectory + "/img1.bmp";
您可以做的是:

string imageDirectory = HttpContext.Current.Server.MapPath("~/images/");
string imageUrl = imageDirectory + "/img1.bmp";
string imageUrl = ResolveClientUrl("~/images/myImage.gif");