2

The code below i use to read lines from file test.txt in my folder Resources of my project.

string[] test = File.ReadAllLines(@"Resources\test.txt");

The properties are already change to "Content" and "Copy Always".

When i run the program, somtimes the path auto change to the Absolute path as: "C:\Users\Documents\Resources\test.txt

And the program error because cannot find the path.

RooKiE
  • 21
  • 3

2 Answers2

0

Yo could use

 Path.Combine(AppDomain.CurrentDomain.BaseDirectory , "Resources", "test.txt"

to get the path.

But to your problem: I think, the problem is the ReadAllLines, because it wants to convert the string to an absolute path. So the problem shouldn't exist anymore, if you localize the string, or even make somenthing like:

var path = "" + "Resources\\test.txt";
var test = File.ReadAllLines(path);

I couldn't test this though because I couldn't reproduce your problem.

MetaColon
  • 2,895
  • 3
  • 16
  • 38
0

You are using a relative path to the file, which relies on the CurrentDirectory being valid. This is either changing, or not being set to the desired directory when the program is executed. You can test this failure with this code:

string CurrentDirectory = Environment.CurrentDirectory;
Log.Trace($"CurrentDirectory = {CurrentDirectory}");
System.IO.File.ReadAllText(@"Resources\test.txt");
Environment.CurrentDirectory = @"C:\Tools";
// changing the current directory will now cause the next command to fail
System.IO.File.ReadAllText(@"Resources\test.txt");

You should not rely on the CurrentDirectory path being set correctly. Get the directory of the current running executable with something like this:

string ExePath = new System.IO.FileInfo(System.Reflection.Assembly.GetExecutingAssembly().Location)
                .Directory.FullName;
string FullPath = System.IO.Path.Combine(ExePath, "Resources", "test.txt");
System.IO.File.ReadAllText(FullPath);
David
  • 1,743
  • 1
  • 18
  • 25