zoukankan      html  css  js  c++  java
  • C#获取相对路径

      

      C#最常使用的相对路径是从当前程序所在路径开始相对寻径,找到要找的路径,即以下两种最简单的方式:

      1. 程序根目录.(即exe程序所在路径)

    //下面两个路径是等价的,都是exe程序所在路径(通常是binDebug下)的Data文件夹下的test文本文件
    string Path1 = @".Data	est.txt"; 
    string Path2 = @"Data	est.txt"; 

      2. 上级目录..

    string Path3 = @"..Data	est.txt";    //程序根目录的上级目录(通常是bin下)的Data文件夹下的test文本文件
    string Path4 = @"....Data	est.txt";  //程序根目录的上两级目录(通常是程序名下)的Data文件夹下的test文本文件

      当然,C#还可以靠指定的方式获得相对路径。应用VS2010创建了一WinForm项目,项目名为RelativePath,放在桌面上。编写代码通过八种特定方式获取相对路径并输出显示,运行效果如下:

      下面简要的介绍一下这八种获得相对路径的方式:

      1. 获取和设置当前目录(该进程从中启动的目录)的完全限定路径

    string str1 = System.Environment.CurrentDirectory;    //Result: C:xxxxxx

      2. 获取应用程序的当前工作目录

    string str2 = System.IO.Directory.GetCurrentDirectory();    //Result: C:xxxxxx

      这个不一定是程序从中启动的目录啊,有可能程序放在C:xxx里,这个函数有可能返回C:Documents and SettingsWSY\,或者C:Program FilesAdobe\,有时不一定返回什么东西,这是程序最后一次操作过的目录,比如你用Word打开了E:docmy.doc这个文件,此时执行这个方法就返回了E:doc了。 

      3. 获取启动了应用程序的可执行文件的路径,不包括可执行文件的名称

    string str3 = System.Windows.Forms.Application.StartupPath;    //Result: C:xxxxxx

      4. 获取启动了应用程序的可执行文件的路径,包括可执行文件的名称

    string str4 = System.Windows.Forms.Application.ExecutablePath;    //Result: C:xxxxxxxxx.EXE

      5. 获取当前 Thread 的当前应用程序域的基目录,它由程序集冲突解决程序用来探测程序集

    string str5 = System.AppDomain.CurrentDomain.BaseDirectory;  //Result: C:xxxxxx

      6. 获取和设置包含该应用程序的目录的名称

    string str6 = System.AppDomain.CurrentDomain.SetupInformation.ApplicationBase;    //Result: C:xxxxxx

      7. 获取当前进程的完整路径,包含文件名

    string str7 = this.GetType().Assembly.Location;    //Result: C:xxxxxxxxx.exe

      8. 获取新的 Process 组件并将其与当前活动的进程关联的主模块的完整路径,包含文件名

    string str8 = System.Diagnostics.Process.GetCurrentProcess().MainModule.FileName;    //Result: C:xxxxxxxxx.vshost.exe

      此外,更多见的通过XML文件配置具体的路径来达到合理的规划配置文件的具体存放位置,如WEB中的配置文件中的路径

    string path = System.AppDomain.CurrentDomain.SetupInformation.ApplicationBase + @"moduleM3ExampleMuColor.txt";
    StreamReader smRead = new StreamReader(path, System.Text.Encoding.Default);  //设置路径
  • 相关阅读:
    2018.10.22-ssoi3979荔枝丹(litchi)
    2018.10.18- oj3969 pd
    2018.10.18-ssoj3970 graph
    【2019年8月版】OCP 071认证考试原题-第38题
    【2019年8月版】OCP 071认证考试原题-第37题
    【2019年8月版】OCP 071认证考试原题-第36题
    【2019年8月版】OCP 071认证考试原题-第35题
    【2019年8月版】OCP 071认证考试原题-第34题
    【2019年8月版】OCP 071认证考试原题-第33题
    【2019年8月】OCP 071认证考试最新版本的考试原题-第32题
  • 原文地址:https://www.cnblogs.com/eniac12/p/4461614.html
Copyright © 2011-2022 走看看