Click here to Skip to main content
15,885,365 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
My sample.csv file looks like this:

ID Name Loc Sal
1 abc usa 2342
2 xyz usa 4567
3 qwe Europe 7864
4 empty row
5 asd Europe 4567

Now I want to write all this data except the rows contains loc as "usa" to new.csv file. In my vb.net winform application I coded for writing all the rows to a new file but haven't got clue to filter the rows. I am not sure wether I can use same logic for this problem or not? Any suggestions please?

VB
Dim ioFile As New System.IO.StreamReader("C:\sample.csv")
 Dim ioLine As String
 Dim ioLines As String
 ioLine = ioFile.ReadLine
 ioLines = "ID,Name,Number,Amount"
 ioLines &= vbCrLf & ioLine
 While Not ioLine = ""
    ioLine = ioFile.ReadLine
    ioLines = ioLines & vbCrLf & ioLine
 End While
 Dim ioWriter As New System.IO.StreamWriter("C:\new.csv")
 ioWriter.WriteLine(ioLines)
 ioFile.Close()
 ioWriter.Close()
Posted

1 solution

You need to test each line for the USA in the location, I personally would use the split function to create an array so that you know you are testing the location value and not finding the value at any location in the line that you have read using ioLine = ioFile.ReadLine

VB
while not ioLine = ""
  ioLine = ioFile.ReadLine
  dim Values as string() = ioLine.split(" ")
  if not values(2) = "usa" then
    iolines += system.environment.newline & ioline
  end if
end while


Documentation on String.split: String.split function[^]
 
Share this answer
 
Comments
Member 8001800 20-Jun-11 6:35am    
if i use this I am getting an error message states "Null Reference Exception was unhandled" points at dim Values as string() = ioLine.split(" ")
Simon_Whale 20-Jun-11 6:37am    
When it errors does ioLine have any values?
Member 8001800 20-Jun-11 6:43am    
it doesn't hold any values
Simon_Whale 20-Jun-11 6:45am    
you need to create a test to make sure the line isn't empty before doing a split
Member 8001800 20-Jun-11 7:05am    
Thank you, its working fine. Additionally, i need to delete empty rows as well. For this I modified above code slightly at, if not values(2) = "usa" or values(2)=" " then But couldn't able to delete empty rows. Any ideas?

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