一样的代码长时间不用也会忘记,虽然网上有很多,但我懒得收索,还是做个笔记记下来省事。
一、 获取当前程序的运行路径
新建了一个项目WpfFile存放于存放于E:\Other-shore目录下;总结网上资源,获取当前程序的运行路径共有以下几种方式:
//获取或设置包含该应用程序的目录的名称。
string C = AppDomain.CurrentDomain.SetupInformation.ApplicationBase; //E:\Other-shore\WpfFile\WpfFile\bin\Debug\
//从当前应用程序域获取基目录获,它由程序集冲突解决程序用来探测程序集。
string D = AppDomain.CurrentDomain.BaseDirectory; // --E:\Other-shore\WpfFile\WpfFile\bin\Debug\
//与C一样
string E = System.Threading.Thread.GetDomain().BaseDirectory; //--E:\Other-shore\WpfFile\WpfFile\bin\Debug\
//从当前环境和平台获取或设置当前工作目录的完全限定路径。
string F = Environment.CurrentDirectory; // --E:\Other-shore\WpfFile\WpfFile\bin\Debug
//从目录中获取应用程序的当前工作目录
string G = System.IO.Directory.GetCurrentDirectory(); // --E:\Other-shore\WpfFile\WpfFile\bin\Debug
//从进程中获取模块的完整路径。
string H = System.Diagnostics.Process.GetCurrentProcess().MainModule.FileName;//--E:\Other-shore\WpfFile\WpfFile\bin\Debug\WpfFile.exe
System.Reflection.Assembly curPath = System.Reflection.Assembly.GetExecutingAssembly();//获取包含当前执行的代码的程序集。
//得到安装程序类SetupLibrary文件的路径,获取这个文件路径所在的目录即得到安装程序的目录;
string path = curPath.Location; //--E:\Other-shore\WpfFile\WpfFile\bin\Debug\WpfFile.exe
还有两种需要添加引用System.Windows.Forms.dll
//获取启动了应用程序的可执行文件的路径,不包括可执行文件的名称。
string A = System.Windows.Forms.Application.StartupPath; //--E:\Other-shore\WpfFile\WpfFile\bin\Debug
//获取启动了应用程序的可执行文件的路径,包括可执行文件的名称。
string B = System.Windows.Forms.Application.ExecutablePath; //--E:\Other-shore\WpfFile\WpfFile\bin\Debug\WpfFile.exe