简体   繁体   中英

ReadAllText method appends file path to the application path

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?

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";

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\\..." )

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"

更改代码如下-

string FileName = @"C:\Test\MyFile.csv";

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);

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