简体   繁体   中英

ReadAllLines() local directory not working

For some reason the ReadAllLines() looks in the wrong folder.

string[] LoadLines = File.ReadAllLines(@"Assets\\\\UserFile.txt");

The "Assets\\UserFile.txt" is located where the exe file is. The Debugger throws a System.IO.DirectoryNotFoundException with a comment:

"Could not find a part of the path C:\\WINDOWS\\SysWOW64\\Assets\\UserFile.txt"

Why is it checking in the wrong folder?

Relative path names are resolved relative to the working directory of the process, not relative to the executable. So presumably your process has a working directory of c:\\Windows\\SysWOW64 .

If your code needs to load assets that are effectively bundled with the application, I'd use embedded resources as a way of not having to worry about physical file paths.

Try this...

string path = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), @"Assets\UserFile.txt");
string[] lines= File.ReadAllLines(path);

Note: This will look in the folder you are executing from so make sure the folder/file exists in there.

If the executing folder is your bin folder, ensure that the file property is set to "Content" and "Always copy" or "Copy when newer" within Visual Studio.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM