Reputation: 1825
I have been getting a wierd excepction that i am not sure what is causing it. In my local machine when i use:
var lines = File.ReadLines("filePath");
foreach(string line in lines)...
This works perfectly without any problems. The code is inside a project built on .NetFramework 4.5. The dll is referenced from a website that is hosted on a .NetFramework 4.0 pool.
Once i upload my work to the host and start using it, all instances in the code that uses the File.ReadLines
throws an exception. I replaced the code with File.ReadAllLines
and it worked.
I have read many questions about this, but i don't think any of them answers why this happens. Could it be the .NetFramework version or is it something else ?
Upvotes: 0
Views: 2351
Reputation: 553
Notice that ReadLines only lets you iterate through the lines once, under the hood that method does something similar to this:
private IENumerable<string> ReadLine(string path)
{
var file = OpenFile(path);
while (file.Read())
{
yield return file.GetLine();
}
file.Close();
}
This means that the file is open until you finish interating through the IEnumerable and is closed as soon as you reach the end of it. Maybe it would be simpler for you to call ReadAllLines, which returns a good old string[] that let's you iterate through it at will.
Upvotes: 3
Reputation: 2936
ReadLine
method was introduced with .NET Framework 4.0, while ReadAllLines
was introduces with .NET Framework 2.0. So, probably the problem is the .NET version.
Upvotes: 1