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的引用后使用


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM