I am new to C#. Created a C# application which reads from a file and does some processing. I have manually put the files under myProject/bin/Debug/files/
(Note: manually copy-pasted file, not sure if i need to import in any way through the application - using SharpDevelop IDE). My code reads the file through
string query = File.ReadAllText(@"files\myfile.txt");
After I built and passed it to a client and it's working fine when they click on myproject.exe
, it can locate the file. But when they trigger it using windows task scheduler, the error they get is:
System.IO.DirectoryNotFoundException: Could not find a part of the path 'C:\\Windows\\system\\files\\myfile.txt'... at extractor.Program.query() in d:\\workspace\\test\\Program.cs:line 81 (this is my local path, shoud show client's folder path instead)
Need help with:
myfile.txt
as necessary, without touching the .exe (without the need to build again) @"files\\myfile.txt"
). Appreciate help.
There are two different paths at play in your error message.
Wrong Local Path
The first is the path where the application tries to find the file. This, in your error is
C:\\Windows\\system\\files\\myfile.txt
This path is searched because File.ReadAllText
, when given a relative path name, will search under the Current Directory, which isn't necessarily the one where your app is installed - it can be changed by calls to Directory.SetCurrentDirectory
, 3rd-party components or even using the Open File Dialog.
What you need to do is not use a relative path, but specify explicitly where your files are. You can do that by taking your currently executing EXE's path and appending files\\myfiles.txt
to it. You can get the current EXE path using Assembly.GetExecutingAssembly().Location
.
Developer path
Your error message seems to point to a path on your developer machine, but this isn't actually where .NET is looking for hte file, but rather the location of the original C# file where the exception was thrown . This is because you included the PDB files which contain extra debug information - this debug information contains the dev workspace path, so you can find the error in your code.
use like this
string path = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetEntryAssembly().Location);
String query = File.ReadAllText(Path.Combine(path, "files\\Test.txt"));
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.