C# Note5:使用相对路径读取文件
2024-08-26 10:54:43
一、C#中使用相对路径读取配置文件
一般Solution的目录结构如下图所示:
(如过看不到某些文件,可以点击 “显示所有文件” 图标)
方法一:由于生成的exe文件在bin\debug目录下,可以使用向上查找目录的方式获取要读取的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(, Application.StartupPath.LastIndexOf("\\"));
fullName = fullName.Substring(, 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(, path.LastIndexOf("\\"));
folderName = path.Substring(path.LastIndexOf("\\") + );
}
return path.Substring(, path.LastIndexOf("\\") + );
}
最新文章
- Leetcode Anagrams
- python的tab自动补全
- bootstrap 分页
- mac 配置jdk maven
- 【HDOJ】4355 Party All the Time
- 疯狂的表单-html5新增表单元素和属性
- Android ListView A~Z快速索引(改进版)
- CSS 文章段落样式
- 关于oracle数据库(11)
- CodeForces 543D:Road Improvement
- SQL Update
- Gym101237C The Palindrome Extraction Manacher、SAM、倍增
- P1087 FBI树 二叉树
- genstr.py
- 数据库使用:sql server/mysql/sqlite
- [转]Sqoop-1.4.4工具import和export使用详解
- POJ_2533_Longest Ordered Subsequence
- TcMalloc的介绍以及Windows下安装使用
- bzoj 3289: Mato的文件管理 莫队+树状数组
- Repeater中服务器按钮