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);
}

 

原文地址:https://www.cnblogs.com/carsonzhu/p/6873602.html