Click here to Skip to main content
15,884,739 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hey Guys,
I have a question which I need a bit of help with. I am writing an import process which has an error threshold of say 20 errors before the file becomes invalid. I have a couple of requirements which are proving a bit tricky.
I need to ignore empty lines at the end of the file and not treat them as error rows (not a problem), but there may also be empty rows inside the file at any position which should cause errors. So the trouble I am having is distinguishing between a row in the file and a row at the end of the file. Bearing in mind that the file could be 1000's of lines long.

Any help is appreciated guys.
Posted

Exact help is difficult - since you don't really specify how you are reading the file. However, I assume you are reading it line-by-line with a StreamReader of some form.
Don't.
Read the whole file with File.ReadAllText into a string.
Trim off the newlines at the end with String.TrimEnd
Convert to individual lines with Split:
VB
Dim text As String = File.ReadAllText("D:\Temp\Text.txt")
text = text.TrimEnd()
Dim lines As String() = text.Split(ControlChars.Lf)
 
Share this answer
 
Comments
frostcox 12-Dec-13 11:26am    
Hey thanks for you answer. If I read the whole file in and store it in memory as a string won't that take up to much memory?
OriginalGriff 12-Dec-13 11:30am    
How big is the file?
1000's of lines isn't much: even if each line was 1000 characters, that would still only be megabytes...and you have how many Gig? :laugh:
It's also generally a lot, lot faster to process than line-by-line access.
frostcox 12-Dec-13 11:37am    
Max file size is about 20 megabytes. Yeah your right it may be worth me re-thinking how I was processing the file. I will run a few tests and observe the results but your solution is by far the easiest to implement.
Thanks Again
OriginalGriff 12-Dec-13 11:45am    
20MB isn't much (think about it, bitmaps can get bigger than that PDQ) - the max size of any object in .NET is 2GB, so you are nowhere near any limits.
You are in for some tricky issues on eliminating the last empty lines from the file ... particularly if you are dealing with large files that you do not want to load into memory. Encoding issues may be problematic.

See: [^] for Jon Skeet's guru-level approach.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900