码迷,mamicode.com
首页 > Windows程序 > 详细

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

时间:2017-01-09 00:14:20      阅读:262      评论:0      收藏:0      [点我收藏+]

标签:class   winform   rect   ret   current   c#   cat   article   alt   

这篇文章主要介绍了C#中winform使用相对路径读取文件的方法,实例分析了C#使用相对路径读取文件的技巧与实际应用,需要的朋友可以参考下

本文实例讲述了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#中winform使用相对路径读取文件的方法

标签:class   winform   rect   ret   current   c#   cat   article   alt   

原文地址:http://www.cnblogs.com/wanzhongjun/p/6262996.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!