120

I have a C# project (Windows Console Application). I have created a folder named Data inside project. There are two text files inside folder Data.

How can I read the text files from "Data" folder. I tried below things.

string[] files = File.ReadAllLines(@"Data\Names.txt")

It is thowing error that file not found.

I have checked some Stackoverflow answers posted before and none of then are working for me.

How can I proceed? Thanks!

skjcyber
  • 5,759
  • 12
  • 40
  • 60

9 Answers9

184

below code should work:

string path = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), @"Data\Names.txt");
string[] files = File.ReadAllLines(path);
Morbia
  • 4,144
  • 3
  • 21
  • 13
  • My folder and files do not exist in the assembly folder :s .. Why is that? – bohem.be May 24 '16 at 15:36
  • 59
    in Visual Studio, mark the file and then set `Build Action` to `Content`, and `Copy to Output Directory` to `Copy always` – Florian Moser Sep 05 '16 at 14:53
  • 4
    Just use @"Data\Name.txt" applying @FlorianMoser notation – Alexandr Sargsyan Jul 03 '17 at 16:16
  • what's that '@' means for? – gumuruh Sep 22 '19 at 12:56
  • @ there is called verbatim string literal, see https://stackoverflow.com/questions/3311988/what-is-the-difference-between-a-regular-string-and-a-verbatim-string – Morbia Sep 24 '19 at 05:50
  • To fully complete this thought, the '@' is there so you don't have to escape the backslask in the path. – Stevers Jan 01 '21 at 15:19
  • I used AppDomain.CurrentDomain.BaseDirectory for the base path and it worked for unit testing as well. – Vlad Feb 18 '21 at 18:02
  • The code in this answer should be used only if you have an intention to fetch the path like this: C:\Users\lenovo\AppData\Local\Temp\Temporary ASP.NET Files\vs\e569ddac\c9182dba\assembly\dl3\e1c0b2a1\3fffb0d1_3b17d801\Data\Names.txt – Saima Feb 01 '22 at 07:21
41

it depends where is your Data folder

To get the directory where the .exe file is:

AppDomain.CurrentDomain.BaseDirectory

To get the current directory:

Environment.CurrentDirectory

Then you can concatenate your directory path (@"\Data\Names.txt")

Massimiliano Peluso
  • 26,379
  • 6
  • 61
  • 70
24

If you need to get all the files in the folder named 'Data', just code it as below

string[] Documents = System.IO.Directory.GetFiles("../../Data/");

Now the 'Documents' consists of array of complete object name of two text files in the 'Data' folder 'Data'.

Uthistran Selvaraj
  • 1,371
  • 1
  • 12
  • 31
19

I have a C# project (Windows Console Application). I have created a folder named Images inside project. There is one ico file called MyIcon.ico. I accessed MyIcon.ico inside Images folder like below.

this.Icon = new Icon(@"../../Images/MyIcon.ico");
josliber
  • 43,891
  • 12
  • 98
  • 133
Ziggler
  • 3,361
  • 3
  • 43
  • 61
15

Copy Always to output directory is set then try the following:

 Directory.SetCurrentDirectory(AppDomain.CurrentDomain.BaseDirectory);
 String Root = Directory.GetCurrentDirectory();
Rickey
  • 7,830
  • 1
  • 19
  • 12
  • 1
    This should be the accepted answer - it is robust whether the file is in a library or in the executable project. – Tullochgorum Mar 27 '20 at 01:58
  • The main idea is that by setting copy always to output directory ,it always copies file/folder under bin folder and AppDomain.CurrentDomain.BaseDirectory returns bin folder path. For instance if you have Products.xlsx under ExcelSettings folder ,you get it with following: Path.Combine(Path.GetDirectoryName(AppDomain.CurrentDomain.BaseDirectory), "ExcelSettings\\Products.xlsx) – erhan355 Nov 22 '21 at 10:25
  • This should be the accepted answer, it's the only one that worked for me! OMG i've search so much, and so many duds.. – Dumitru Daniel Jun 10 '22 at 08:54
1

This was helpful for me, if you use the

var dir = Directory.GetCurrentDirectory()

the path fill be beyond the current folder, it will incluide this path \bin\debug What I recommend you, is that you can use the

string dir = Directory.GetParent(Directory.GetCurrentDirectory()).Parent.Parent.FullName

then print the dir value and verify the path is giving you

Tony Dong
  • 3,213
  • 1
  • 29
  • 32
0

For Xamarin.iOS you can use the following code to get contents of the file if file exists.

var documents = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
var filename = Path.Combine(documents, "xyz.json");
if (File.Exists(filename))
{
var text =System.IO.File.ReadAllText(filename);
}
-1

Use this Code for read all files in folder and sub-folders also

class Program
{
    static void Main(string[] args)
    {

        getfiles get = new getfiles();
        List<string> files =  get.GetAllFiles(@"D:\Document");

        foreach(string f in files)
        {
            Console.WriteLine(f);
        }


        Console.Read();
    }


}

class getfiles
{
    public List<string> GetAllFiles(string sDirt)
    {
        List<string> files = new List<string>();

        try
        {
            foreach (string file in Directory.GetFiles(sDirt))
            {
                files.Add(file);
            }
            foreach (string fl in Directory.GetDirectories(sDirt))
            {
                files.AddRange(GetAllFiles(fl));
            }
        }
        catch (Exception ex)
        {

            Console.WriteLine(ex.Message);
        }



        return files;
    }
}
Ris
  • 7
  • 1
-1
string myFile= File.ReadAllLines(Application.StartupPath.ToString() + @"..\..\..\Data\myTxtFile.txt")
Gibolt
  • 42,564
  • 15
  • 187
  • 127
  • 4
    Please add some text detailing why this works/what it does – Gibolt Jan 16 '19 at 22:33
  • 2
    While this might answer the authors question, it lacks some explaining words and/or links to documentation. Raw code snippets are not very helpful without some phrases around them. You may also find [how to write a good answer](https://stackoverflow.com/help/how-to-answer) very helpful. Please [edit] your answer - [From Review](https://stackoverflow.com/review/low-quality-posts/21950637) – Nick Jan 17 '19 at 03:10