zoukankan      html  css  js  c++  java
  • 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);
    }

     

  • 相关阅读:
    博客基础_django入门_python从入门到实践_用户登陆、注销与注册
    博客基础_django_python从入门到实践_添加主题_添加条目_编辑条目
    python学习(六)
    python作业(五)
    python学习(五)
    python学习(四)
    python作业(三)
    python学习(三)
    python作业(二)
    python学习(二)
  • 原文地址:https://www.cnblogs.com/carsonzhu/p/6873602.html
Copyright © 2011-2022 走看看