几种方法如下:
非Web程序

1.AppDomain.CurrentDomain.BaseDirectory

2.Environment.CurrentDirectory

3.HttpRuntime.BinDirectory

The path to the current application's/bin directory.

Web程序

HttpCurrent.Context.Server.Mappath();

---------------------------------------------------------------

HttpContext.Current

返回当前请求的 HttpContext 对象。如此我们就可以直接访问Request、Response、Session、Application等对象,和Page中访问等同。
我们无需再将Page用参数的方式传递到我们的类库对象中。

HttpContext.Current.Session["name"] = "猪八戒";
string name = HttpContext.Current.Request.Param["name"];
HttpContext.Current.Response.Write("猪八戒好吃懒做!");

HttpRuntime

为当前应用程序提供一组 ASP.NET 运行时服务。我们可以通过这个类获得当前ASP.NET工程的一些信息。

HttpRuntime.AppDomainAppVirtualPath : 项目虚拟路径
HttpRuntime.AppDomainAppPath : 项目物理路径
HttpRuntime.BinDirectory : BIN目录物理路径
HttpRuntime.ClrInstallDirectory : CLR安装路径(可以用来获取CLR版本号)

Response.Write(string.Format("AppDomainAppId: {0}<br>", HttpRuntime.AppDomainAppId));
Response.Write(string.Format("AppDomainAppPath: {0}<br>", HttpRuntime.AppDomainAppPath));
Response.Write(string.Format("AppDomainAppVirtualPath: {0}<br>", HttpRuntime.AppDomainAppVirtualPath));
Response.Write(string.Format("AppDomainId: {0}<br>", HttpRuntime.AppDomainId));
Response.Write(string.Format("AspInstallDirectory: {0}<br>", HttpRuntime.AspInstallDirectory));
Response.Write(string.Format("BinDirectory: {0}<br>", HttpRuntime.BinDirectory));
Response.Write(string.Format("ClrInstallDirectory: {0}<br>", HttpRuntime.ClrInstallDirectory));
Response.Write(string.Format("CodegenDir: {0}<br>", HttpRuntime.CodegenDir));
Response.Write(string.Format("IsOnUNCShare: {0}<br>", HttpRuntime.IsOnUNCShare.ToString()));
Response.Write(string.Format("MachineConfigurationDirectory: {0}<br>", HttpRuntime.MachineConfigurationDirectory));

输出:
AppDomainAppId: /LM/W3SVC/1/Root/Learn.Test.Web
AppDomainAppPath: D:\System\My Documents\Visual Studio Projects\Learn.Test\Learn.Test.Web\
AppDomainAppVirtualPath: /Learn.Test.Web
AppDomainId: /LM/W3SVC/1/Root/Learn.Test.Web-9-127652564154400560
AspInstallDirectory: C:\WINDOWS\Microsoft.NET\Framework\v1.1.4322
BinDirectory: D:\System\My Documents\Visual Studio Projects\Learn.Test\Learn.Test.Web\bin\
ClrInstallDirectory: c:\windows\microsoft.net\framework\v1.1.4322
CodegenDir: C:\WINDOWS\Microsoft.NET\Framework\v1.1.4322\Temporary ASP.NET Files\learn.test.web\41680132\7c880883
IsOnUNCShare: False
MachineConfigurationDirectory: c:\windows\microsoft.net\framework\v1.1.4322\Config

HostingEnvironment

string siteName = HostingEnvironment.SiteName;
string appPath = HostingEnvironment.ApplicationVirtualPath;
string phyPath = HostingEnvironment.ApplicationPhysicalPath;
string adminPath = HostingEnvironment.MapPath("~/Admin");

ApplicationManager.GetApplicationManager().ShutdownApplication(HostingEnvironment.ApplicationID);

灵活运用技巧:

当使用非WEB程序或使用异步调用时,想要取得根目录下的某目录可以使用如下代码:

HttpRuntime.BinDirectory + "../目录名";

获取网站根目录的方法有几种如:

Server.MapPath(Request.ServerVariables["PATH_INFO"])
Server.MapPath("/")
Server.MapPath("")
Server.MapPath(".")
Server.MapPath("../")
Server.MapPath("..") 
Page.Request.ApplicationPath
运行结果:
C:\Inetpub\wwwroot\EnglishClub\manage\WebForm1.aspx
C:\Inetpub\wwwroot\
C:\Inetpub\wwwroot\EnglishClub\manage
C:\Inetpub\wwwroot\EnglishClub\manage
C:\Inetpub\wwwroot\EnglishClub\
C:\Inetpub\wwwroot\EnglishClub

以上的方法可以在.aspx中访问,但是如果你在。cs文件就不能用。

HttpContext.Current.Server.MapPath();
System.Web.HttpContext.Current.Request.PhysicalApplicationPath

在.cs文件中可以用。

但是HttpContext.Current.Server.MapPath();这个获取的是文件的路径而不是根目录。

只有System.Web.HttpContext.Current.Request.PhysicalApplicationPath    这个才是获取的根目录,在写获取数据库路径是应该用这个,其他的都有问题。

测试过,在有些web项目的cs文件中可以这样用。但是最好是用System.Web.HttpContext.Current.Server.MapPath("/SystemManage/Hotel/LocList.xml");

在类库项目中,这个通常是不能用的,这个时候需要引用程序集,引用命名空间System.Web;才行。

System.Environment.CurrentDirectory + @"\IPMS.Web\aboutMe.txt"

HttpContext.Current.Server.MapPath("/") 未将对象设置到对象的实例异常。

多线程中的System.Web.HttpContext.Current.Server.MapPath("/")

多线程中Server.MapPath会失效。。。

网上找到几种解决方法,现在整理如下:

第一种:

System.Web.HttpContext.Current.Server.MapPath("/")  这个常用来表示网站的根目录,但是在多线程中,会发生未将对象引用设置到对象的实例。 所以不要分布在不同的类中,尽量在一个全局位置,然后其它类共用这个,毕竟网站的目录是不会改变的,可以用一个静态变量表示。

该方法:不太好;

第二种:

如果需要是WEB应用的目录下就很好办啊。假设web根目录为:c:\www,而DB放在www目录下的话则可以这样。  System.AppDomain.CurrentDomain.BaseDirectory.ToString() + ConfigurationManager.AppSettings["dbPath"]就可以了
我找到办法了,就是上面的

这个是一种方法,就是将路径下载配置文件中从配置文件读取,感觉还行。

第三种:

在多线程里面使用HttpContext.Current,HttpContext.Current是得到null的.    20150703 解释下为什么当前请求上下文会为null,因为多线程情况下,当前线程可能并非http请求处理线程,根本没发生请求,所以无法获取到HttpContext就是null.

这么用:       

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
public static string MapPath(string strPath)
      {
          if (HttpContext.Current != null)
          {
              return HttpContext.Current.Server.MapPath(strPath);//有http请求
          }
          else //非web程序引用         
          {
              strPath = strPath.Replace("/""\\");
              if (strPath.StartsWith("\\"))
              {
                  //strPath = strPath.Substring(strPath.IndexOf('\\', 1)).TrimStart('\\');                            strPath = strPath.TrimStart('\\');               
              }
              return System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, strPath);
          }
      }

C#获取Web和非Web程序的目录的更多相关文章

  1. C#里面获取web和非web项目路径

    非Web程序获取路径几种方法如下: 1.AppDomain.CurrentDomain.BaseDirectory  2.Environment.CurrentDirectory 3.HttpRunt ...

  2. C#如何加载程序运行目录外的程序集

    我们的应用程序部署的时候,目录结构一般不会只有运行程序的目录这一个,我们可能在运行目录下建子目录,也可能使用System32目录,也可能使用其它第三方的程序集..Net程序集 首先会在GAC中搜索相应 ...

  3. (转)C#如何加载程序运行目录外的程序集

    https://www.cnblogs.com/guanglin/p/3200989.html 我们的应用程序部署的时候,目录结构一般不会只有运行程序的目录这一个,我们可能在运行目录下建子目录,也可能 ...

  4. C#如何加载程序运行目录外的程序集 (转)

    ---恢复内容开始--- 尼玛,为了这个问题,纠结到差点吐出干血,赶紧记下来! 源地址:http://blog.csdn.net/dyllove98/article/details/9391325 我 ...

  5. 一步一步学习SignalR进行实时通信_9_托管在非Web应用程序

    原文:一步一步学习SignalR进行实时通信_9_托管在非Web应用程序 一步一步学习SignalR进行实时通信\_9_托管在非Web应用程序 一步一步学习SignalR进行实时通信_9_托管在非We ...

  6. 用JQuery中的Ajax方法获取web service等后台程序中的方法

    用JQuery中的Ajax方法获取web service等后台程序中的方法 1.准备需要被前台html页面调用的web Service,这里我们就用ws来代替了,代码如下: using System; ...

  7. C#取得Web程序和非Web程序的根目录的N种取法

    取得控制台应用程序的根目录方法方法1.Environment.CurrentDirectory 取得或设置当前工作目录的完整限定路径方法2.AppDomain.CurrentDomain.BaseDi ...

  8. 【.net深呼吸】非 Web 项目使用缓存

    从.net 4 开始,非web项目也可以使用缓存技术,故曰:.net 4 乃框架成熟之标志也. 对于缓存嘛,耍过 ASP.NET 的伙伴们肯定知道,这么说吧,就是将一些使用频率较高的数据放于内存中,并 ...

  9. springboot 创建非web项目及数据源简单使用

    项目组马上要使用springboot来重构程序,首先要对几个比较小的非web项目重构,所以新手入门,简单做了个小例子 代码结构如下: dao层 package com.mysping.myboot00 ...

随机推荐

  1. centos:时间同步

    转自:https://blog.csdn.net/u011391839/article/details/62892020 Linux的时间分为System Clock(系统时间)和Real Time ...

  2. Intellij IDEA 配置Subversion插件时效解决方法

    在使用Intellij的过程中,突然发现svn不起效了,在VCS–>Checkout from Version Control中也未发现Subversion这一项.如下图: 一.原因查找 经过分 ...

  3. CXF实战之拦截器Interceptor(四)

    拦截器(Interceptor)是CXF功能最基本的扩展点,能够在不正确核心模块进行改动的情况下.动态加入非常多功能.拦截器和JAX-WS Handler.Filter的功能相似,当服务被调用时.就会 ...

  4. [精品]CAD批量处理工具

     需要此工具请Q:3567 618 336 CAD批量处理工具是基于AutoCAD二次开发的批处理插件.将程序加载到CAD中,使用自定义的Lisp代码就可对多个文档进行批量操作. 1.文件说明 CAD ...

  5. javascript数组操作大全,数组方法总汇

    1. shift:删除原数组第一项,并返回删除元素的值:如果数组为空则返回undefined var a = [1,2,3,4,5]; var b = a.shift(); //a:[2,3,4,5] ...

  6. LintCode: 3 Sum

    C++ 把3个数求和,转变为2个数求和 1. 把数组排序 2. 注意过滤重复值 3. 从前到后遍历,游标i 4. 从后边数中找start + end = -arr[i]的2 sum 5. start ...

  7. Windows系统Ionic安装教程/Ionic环境配置

    原文链接:http://blog.csdn.net/superjunjin/article/details/43412017 参考文章 Cordova 3.x 基础(1) -- 环境搭建(Window ...

  8. 微信小程序 - 组件传值给调用页面

    演示如下(可以ctrl+鼠标放大或者下载GIF图片) 1. 先组件定义事件“checkbox”(组件内事件) 2. 调用页面调用它需要加bind:事件名 = 调用页面事件名(bind即绑定调用组件“o ...

  9. Linux中磁盘分区、格式化、挂载等管理

    1. 添加磁盘,查看磁盘状况 [root@db1 /]# fdisk -l Disk /dev/sda: bytes heads, sectors/track, cylinders Units = c ...

  10. Window10中创建目录连接点

    使用命令: mklink /J "junction point name" "target directory" 如,我有一个文件夹在D:\aa,想存在相同的目 ...