我的项目树(解决方案资源管理器)包含一个名为Configs的文件夹(它直接位于根目录中)。 如何从中读取文件 - 我已经尝试过
string ss1 = File.ReadAllText("\\..\\..\\Configs\\Settings.txt");
但是没有这样的文件(路径的一部分)
答案 0 :(得分:0)
如果您想获取项目文件夹,请转到一个级别,以下语言扩展方法应该适合您。
将此课程放入您的项目
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);
}
}
用法
string configurationFile =
Path
.Combine(AppDomain.CurrentDomain.BaseDirectory.CurrentProjectFolder(), "Configs");
if (File.Exists(configurationFile))
{
string fileContents = File.ReadAllText(configurationFile);
}