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;

另一种方式:

 1     /// <summary>
 2     /// 获取应用程序根路径
 3     /// </summary>
 4     private static string GetApplicationPath()
 5     {
 6         string path = Application.StartupPath;
 7         //string path=AppDomain.CurrentDomain.BaseDirectory; //另一种获取方式
 8         string folderName = String.Empty;
 9         while (folderName.ToLower() != "bin")
10         {
11             path = path.Substring(0, path.LastIndexOf("\\"));
12             folderName = path.Substring(path.LastIndexOf("\\") + 1);
13         }
14         return path.Substring(0, path.LastIndexOf("\\") + 1);
15     }
posted @ 2014-06-26 16:42  天琊蓝  阅读(5953)  评论(0编辑  收藏  举报