C# 从项目目录中的文件夹读取文件

C# 从项目目录中的文件夹读取文件,c#,C#,我的项目树(解决方案资源管理器)包含一个名为Configs的文件夹(它直接位于根目录中)。 如何从中读取文件-我已经尝试过了 string ss1 = File.ReadAllText("\\..\\..\\Configs\\Settings.txt"); 但是没有这样的文件(路径的一部分)如果您想要获取项目文件夹,那么向下一级,下面的语言扩展方法应该适合您 将该类放入您的项目中 using System; using System.Collections.Generic; using Sy

我的项目树(解决方案资源管理器)包含一个名为Configs的文件夹(它直接位于根目录中)。 如何从中读取文件-我已经尝试过了

string ss1 = File.ReadAllText("\\..\\..\\Configs\\Settings.txt");

但是没有这样的文件(路径的一部分)

如果您想要获取项目文件夹,那么向下一级,下面的语言扩展方法应该适合您

将该类放入您的项目中

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
public static class Extensions
{
    /// <summary>
    /// Given a folder name return all parents according to level
    /// </summary>
    /// <param name="FolderName">Sub-folder name</param>
    /// <param name="level">Level to move up the folder chain</param>
    /// <returns>List of folders dependent on level parameter</returns>
    public static string UpperFolder(this string FolderName, Int32 level)
    {
        List<string> folderList = new List<string>();

        while (!string.IsNullOrEmpty(FolderName))
        {
            var temp = Directory.GetParent(FolderName);
            if (temp == null)
            {
                break;
            }
            FolderName = Directory.GetParent(FolderName).FullName;
            folderList.Add(FolderName);
        }

        if (folderList.Count > 0 && level > 0)
        {
            if (level - 1 <= folderList.Count - 1)
            {
                return folderList[level - 1];
            }
            else
            {
                return FolderName;
            }
        }
        else
        {
            return FolderName;
        }
    }
    public static string CurrentProjectFolder(this string sender)
    {
        return sender.UpperFolder(3);
    }
}

AppDomain.CurrentDomain.BaseDirectory从VS运行应用程序时,您的基本目录位于bin\debug下。我们不知道您的文件系统布局或项目结构,您可以轻松进行一些研究,a)找出当前工作目录,b)验证显示的相对路径是否存在于该目录中。
string configurationFile = 
    Path
    .Combine(AppDomain.CurrentDomain.BaseDirectory.CurrentProjectFolder(), "Configs");

if (File.Exists(configurationFile))
{
    string fileContents = File.ReadAllText(configurationFile);
}