Read and Write from Text File

Shaitan00

Well-known member
Joined
Aug 11, 2003
Messages
343
Location
Hell
Error Reading from Text File [Lenght 0]

Quicker question, more to the point [sorry for my previous book, wont happen again].

I am reading from a text file and storing peices of each line read into strings.

Code:
while ((line = sr.ReadLine()) != null)
{
string Code = "";
string Description = "";
Code = line.Substring(0,line.IndexOf(" "));
}

The problem occurs when reading the text file, there is a line with Lenght 0 [empty line] and this causes C# to halt with the error "The file could not be read: Length cannot be less than zero.Parameter name: length".

How can I detect this so that the code continues to read until the end of the actual file?
 
Last edited by a moderator:
It is already nested in a Try/Catch loop.

try
{
string line;
while ((line = sr.ReadLine()) != null)
{
string Code = "";
Code = line.Substring(0,line.IndexOf(" "));
Console.WriteLine(line);
}
}

catch (Exception e)
{
Console.WriteLine("The file could not be read:");
Console.WriteLine(e.Message);
}
 
Sorry Shaitan00 not done this before myself , but in one of the books I have there is a method of the streamreader called Peek that checks for the end of a file. Hope this helps but out of my depth on this one....
 
use the IndexOf method :)
C#:
			StreamReader sReader=new StreamReader(new FileStream(@"C:\skip lines.txt",FileMode.Open));
			string line=null;

			while(sReader.Peek()!=-1)
			{
				line=sReader.ReadLine();
				if(line.Length!=0)
				{
					if(line.IndexOf("//")==-1) // if // doesnt exist in the line
					{
						Console.WriteLine(line);
					}
				}
			}
			sReader.Close();
 
Back
Top