2015-12-24 4 views
0

В моем дереве проектов (explorer) содержится папка с именем Configs (она находится в корневом каталоге). Как прочитать файл из него - я попыталсяПрочитать файл из папки внутри каталога проекта

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

но нет такого файла (часть пути)

+0

AppDomain.CurrentDomain.BaseDirectory http://stackoverflow.com/questions/6041332/best-way- to-get-application-folder-path – Arshad

+3

Когда вы запускаете приложение из VS, базовый каталог находится в * bin \ debug * – AsfK

+0

Мы не знаем ваш формат файловой системы ни ваша структура проекта, вы можете легко провести некоторое исследование и а) узнать текущий рабочий каталог и b) проверить, существует ли относительный путь, который вы показываете, из этого каталога. – CodeCaster

ответ

0

Если вы хотите, чтобы получить папку проекта спуститесь на один уровень на следующем языке метод расширения должен работать на вас.

Full code sample

Поместите этот класс в проект

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); 
} 
Смежные вопросы