惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

N
Netflix TechBlog - Medium
Blog — PlanetScale
Blog — PlanetScale
月光博客
月光博客
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
CTFtime.org: upcoming CTF events
CTFtime.org: upcoming CTF events
爱范儿
爱范儿
量子位
博客园 - 聂微东
Engineering at Meta
Engineering at Meta
WordPress大学
WordPress大学
GbyAI
GbyAI
MyScale Blog
MyScale Blog
IT之家
IT之家
P
Proofpoint News Feed
M
MIT News - Artificial intelligence
The Cloudflare Blog
H
Hackread – Cybersecurity News, Data Breaches, AI and More
Hugging Face - Blog
Hugging Face - Blog
The Register - Security
The Register - Security
Microsoft Security Blog
Microsoft Security Blog
博客园_首页
MongoDB | Blog
MongoDB | Blog
F
Fortinet All Blogs
博客园 - 三生石上(FineUI控件)
Y
Y Combinator Blog
雷峰网
雷峰网
V
Visual Studio Blog
酷 壳 – CoolShell
酷 壳 – CoolShell
Last Week in AI
Last Week in AI
博客园 - 叶小钗
D
DataBreaches.Net
B
Blog
B
Blog RSS Feed
大猫的无限游戏
大猫的无限游戏
aimingoo的专栏
aimingoo的专栏
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
The GitHub Blog
The GitHub Blog
云风的 BLOG
云风的 BLOG
Recent Announcements
Recent Announcements
阮一峰的网络日志
阮一峰的网络日志
小众软件
小众软件
腾讯CDC
T
Threat Research - Cisco Blogs
SecWiki News
SecWiki News
Martin Fowler
Martin Fowler
D
Docker
Cisco Talos Blog
Cisco Talos Blog
T
Tenable Blog
Webroot Blog
Webroot Blog
宝玉的分享
宝玉的分享

博客园 - 文强

sql优化的几种方式 UpdatePanel 无刷新弹出窗口 .net web 点击链接在页面指定位置显示DIV的问题 重建主键 sql 日期时间格式转换 UpdatePanel无法直接弹出窗口的解决 A标签执行JS脚本 Guid 的几种形式 iis 5.1 连接 sql 2005 CSS 垂直居中 js 获取服务器控件 js CSS VS 打包升成可自动升级的安装包 js 弹出页面传值 提示消息后跳转 spoolsv.exe 报错,无法打印 C# web 网页刷新时数据集的保存和应用 在网页中插入CSS样式表的几种方法
C#获取文件的当前路径
文强 · 2013-07-03 · via 博客园 - 文强

C#获取文件的当前路径

1. System.Diagnostics.Process.GetCurrentProcess().MainModule.FileName

-获取模块的完整路径。

2.System.Environment.CurrentDirectory

-获取和设置当前目录(该进程从中启动的目录)的完全限定目录。

3.System.IO.Directory.GetCurrentDirectory()

-获取应用程序的当前工作目录。这个不一定是程序从中启动的目录啊,

4.System.AppDomain.CurrentDomain.BaseDirectory

-获取程序的基目录。

5.System.AppDomain.CurrentDomain.SetupInformation.ApplicationBase

-获取和设置包括该应用程序的目录的名称。

6. System.Windows.Forms.Application.StartupPath

-获取启动了应用程序的可执行文件的路径。效果和2、5一样。只是5返回的字符串后面多了一个"\"而已

7.System.Windows.Forms.Application.ExecutablePath

-获取启动了应用程序的可执行文件的路径及文件名,效果和1一样。

对于Windows程序 和Web 应用程序来说,他们运行的路径是不一样的,所以关键是判断当前运行的程序是哪种程序.于是我们可以使用如下的代码

string path = "";

if (System.Environment.CurrentDirectory ==AppDomain.CurrentDomain.BaseDirectory)//Windows应用程序则相等

...{

path = AppDomain.CurrentDomain.BaseDirectory;

}

else

...{

path = AppDomain.CurrentDomain.BaseDirectory + "Bin\";

}

这样如果我们写了一个类库,类库中用到了Assembly.LoadFrom,由于是通用类库,所以可能用到Windows程序中也可能用到Web中,那么用上面的代码就很方便了.

1、Server.MapPath

2、System.Windows.Forms.StartupPath

3、Type.Assembly.Location

方法2可以应用于控制台应用程序,WinForm应用程序,Windows服务,方法1可以应用于Web应用程序,方法3都可以应用。

但方法3是加载应用程序的路径。如果是Web应用程序,取得的路径是:C:\WINDOWS\Microsoft.NET\Framework\v1.1.4322\Temporary ASP.NET Files目录。所以Web项目还是使用Server.MapPath吧。否则建议使用方法2。如果自己新建类库。可以加入对System.Windows.Forms.StartupPath的引用后使用