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!
Answers. You will likely want to have the contents of the Data folder copied to your output folder, which will allow you to access the file using the relative path name: Data\myTextFile. txt. To have the file copied to your output folder, select that file, change its' type to Content and select Copy if newer.
readdir() Method. The fs. readdir() method is used to asynchronously read the contents of a given directory. The callback of this method returns an array of all the file names in the directory.
To extract filename from the file, we use “GetFileName()” method of “Path” class. This method is used to get the file name and extension of the specified path string. The returned value is null if the file path is null. Syntax: public static string GetFileName (string path);
below code should work:
string path = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), @"Data\Names.txt"); string[] files = File.ReadAllLines(path);
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"
)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With