zoukankan      html  css  js  c++  java
  • C# Note5:使用相对路径读取文件

    一、C#中使用相对路径读取配置文件

    一般Solution的目录结构如下图所示:

    (如过看不到某些文件,可以点击 “显示所有文件” 图标)

    方法一:由于生成的exe文件在bindebug目录下,可以使用向上查找目录的方式获取要读取的xml文件

    string tPath = @"../../Converts/XMLFile1.xml";
    FileInfo file = new FileInfo(fileName);
    string  fullName = file.FullName;

    注:使用@的意思是不转义/

    方法二:获取exe文件的路径进行截取,分两次进行,然后拼接文件名,形成全路径

    string tPath = @"XMLFile1.xml"; 
    string fullName = Application.StartupPath.Substring(0, Application.StartupPath.LastIndexOf("\"));
    fullName
    = fullName.Substring(0, fullName.LastIndexOf("\")) + "\" + tPath;

    方法三:

    /// <summary>
    /// 获取应用程序根路径
    /// </summary>
    private static string GetApplicationPath()
    {
            string path = Application.StartupPath;
            //string path=AppDomain.CurrentDomain.BaseDirectory; //另一种获取方式
            string folderName = String.Empty;
            while (folderName.ToLower() != "bin")
            {
                path = path.Substring(0, path.LastIndexOf("\"));
                folderName = path.Substring(path.LastIndexOf("\") + 1);
            }
            return path.Substring(0, path.LastIndexOf("\") + 1);
    }

     

  • 相关阅读:
    出差常熟,郁闷中 沧海
    ABAP中程序之间传递参数的办法 沧海
    LSMW中出现No logical path specified. 沧海
    请认真对待生活 沧海
    escape sequence 沧海
    休假一周 沧海
    Print Program and Form Modify 沧海
    下周回南京 沧海
    LO020真麻烦 沧海
    函数讲解函数列表(ZT) 沧海
  • 原文地址:https://www.cnblogs.com/carsonzhu/p/6873602.html
Copyright © 2011-2022 走看看