0

My project tree (solution explorer)contains a folder named Configs (it is directly in root directory). How to read a file from it - I have tried

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

but there is no such file (part of path)

curiousity
  • 4,703
  • 8
  • 39
  • 59
  • AppDomain.CurrentDomain.BaseDirectory http://stackoverflow.com/questions/6041332/best-way-to-get-application-folder-path – Mohammad Arshad Alam Dec 24 '15 at 10:32
  • 3
    When you run the app from VS you base directory is under *bin\debug* – AsfK Dec 24 '15 at 10:33
  • We don't know your filesystem layout nor your project structure, you can easily do some research and a) find out the current working directory and b) validate whether the relative path you show exists from that directory. – CodeCaster Dec 24 '15 at 10:36

1 Answers1

0

If you want to get the project folder then go down one level the following language extension method should work for you.

Full code sample

Place this class into your project

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);
    }
}

Usage

string configurationFile = 
    Path
    .Combine(AppDomain.CurrentDomain.BaseDirectory.CurrentProjectFolder(), "Configs");

if (File.Exists(configurationFile))
{
    string fileContents = File.ReadAllText(configurationFile);
}
Karen Payne
  • 4,341
  • 2
  • 14
  • 31