C#中winform使用相对路径读取文件的方法

实例讲述了C#中winform使用相对路径读取文件的方法。分享给大家供大家参考。具体分析如下:
目录结构如下图所示:
C#中winform使用相对路径读取文件的方法

C#中winform使用相对路径读取文件的方法

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

复制代码 代码如下:
string haarXmlPath = @"../../haarcascade_frontalface_alt_tree.xml";
FileInfo file = new FileInfo(fileName);
string fullName = file.FullName;

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

复制代码 代码如下:
string haarXmlPath = @"haarcascade_frontalface_alt_tree.xml";
string fullName = Application.StartupPath.Substring(0, Application.StartupPath.LastIndexOf("\"));
fullName = fullName.Substring(0, fullName.LastIndexOf("\")) + "\" + haarXmlPath;

另一种方式:
复制代码 代码如下:

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

希望本文所述对大家的C#程序设计有所帮助。

转载于:https://blog.51cto.com/1388969/2084286

  • 2
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值