Reputation: 6909
I am using ReadAllText method to read file contents into a string but I keep getting an exception file not found. That happened because, for some reason, ReadAllText appends file path to the application path and attempts to find it:
Additional information: Could not find a part of the path 'c:\Projects\MyApp1\MyApp1\bin\Debug\C\Test\MyFile.csv'.
string FileName ="C:\Test\MyFile.csv";
string allText = File.ReadAllText(fileName, encoding);
How can I fix this issue?
Upvotes: 1
Views: 1335
Reputation: 8545
Change code as below-
string FileName = @"C:\Test\MyFile.csv";
Upvotes: 0
Reputation: 9244
In C# you need to escape the \
character when you have enclosed it in a string that is enclosed in quotes. Escaping is needed because the \
character is treated as a way of displaying special characters in a text string. Change the code to the following:
string FileName ="C\\Test\\MyFile.csv";
string allText = File.ReadAllText(fileName, encoding);
You could also use the special @
operator to specify a verbatim string literal. That would look like the following following:
string FileName =@"C\Test\MyFile.csv";
string allText = File.ReadAllText(fileName, encoding);
Finally, You are missing the :
character in your path. The code should actually look like the following:
string FileName = @"C:\Test\MyFile.csv";
string allText = File.ReadAllText(fileName, encoding);
Upvotes: 0
Reputation: 35290
You have a typo: C\
should be C:\
. Also you need to escape your slashes:
"C:\\Test\\MyFile.csv"
or make the whole string a literal:
@"C:\Test\MyFile.csv"
Upvotes: 1
Reputation: 115749
Your FileName
is off. First, you're missing a colon between drive name and forward slash; it should be C:\
. Second, you should be properly escaping the \
character, like this: C:\\Test\\...
(or, using verbatim strings, @"C:\Test\..."
)
Upvotes: 1
Reputation: 26856
You have missed :
in filename, thus it looks like relative path for File.ReadAllText
method, so it appends this to the path where executable file is located. Also \
symbols should be escaped in the string.
Just change it to
string FileName =@"C:\Test\MyFile.csv";
Upvotes: 1