C#获取文件的当前路径
1. System.Diagnostics.Process.GetCurrentProcess().MainModule.FileName
-獲取模塊的完整路徑。
2.System.Environment.CurrentDirectory
-獲取和設(shè)置當(dāng)前目錄(該進(jìn)程從中啟動(dòng)的目錄)的完全限定目錄。
3.System.IO.Directory.GetCurrentDirectory()
-獲取應(yīng)用程序的當(dāng)前工作目錄。這個(gè)不一定是程序從中啟動(dòng)的目錄啊,
4.System.AppDomain.CurrentDomain.BaseDirectory
-獲取程序的基目錄。
5.System.AppDomain.CurrentDomain.SetupInformation.ApplicationBase
-獲取和設(shè)置包括該應(yīng)用程序的目錄的名稱。
6. System.Windows.Forms.Application.StartupPath
-獲取啟動(dòng)了應(yīng)用程序的可執(zhí)行文件的路徑。效果和2、5一樣。只是5返回的字符串后面多了一個(gè)"\"而已
7.System.Windows.Forms.Application.ExecutablePath
-獲取啟動(dòng)了應(yīng)用程序的可執(zhí)行文件的路徑及文件名,效果和1一樣。
?
對(duì)于Windows程序 和Web 應(yīng)用程序來(lái)說(shuō),他們運(yùn)行的路徑是不一樣的,所以關(guān)鍵是判斷當(dāng)前運(yùn)行的程序是哪種程序.于是我們可以使用如下的代碼
string path = "";
if (System.Environment.CurrentDirectory ==AppDomain.CurrentDomain.BaseDirectory)//Windows應(yīng)用程序則相等
...{
path = AppDomain.CurrentDomain.BaseDirectory;
}
else
...{
path = AppDomain.CurrentDomain.BaseDirectory + "Bin\";
}
這樣如果我們寫了一個(gè)類庫(kù),類庫(kù)中用到了Assembly.LoadFrom,由于是通用類庫(kù),所以可能用到Windows程序中也可能用到Web中,那么用上面的代碼就很方便了.
1、Server.MapPath
2、System.Windows.Forms.StartupPath
3、Type.Assembly.Location
方法2可以應(yīng)用于控制臺(tái)應(yīng)用程序,WinForm應(yīng)用程序,Windows服務(wù),方法1可以應(yīng)用于Web應(yīng)用程序,方法3都可以應(yīng)用。
但方法3是加載應(yīng)用程序的路徑。如果是Web應(yīng)用程序,取得的路徑是:C:\WINDOWS\Microsoft.NET\Framework\v1.1.4322\Temporary ASP.NET Files目錄。所以Web項(xiàng)目還是使用Server.MapPath吧。否則建議使用方法2。如果自己新建類庫(kù)。可以加入對(duì)System.Windows.Forms.StartupPath的引用后使用
轉(zhuǎn)載于:https://www.cnblogs.com/joy-126/archive/2012/02/08/2342559.html
總結(jié)
以上是生活随笔為你收集整理的C#获取文件的当前路径的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: 求一个难过个性签名!
- 下一篇: hdu3368 Reversi