Hey, i have a question: Is it possible to replace a value in a .csv file using VB????
Here is an example of what im talking about:
Column1, Column2, Column3, Column4, Column5
Value1, Value2, Value3, ., Vlaue5
i need to replace ,., with , Value4,
Printable View
Hey, i have a question: Is it possible to replace a value in a .csv file using VB????
Here is an example of what im talking about:
Column1, Column2, Column3, Column4, Column5
Value1, Value2, Value3, ., Vlaue5
i need to replace ,., with , Value4,
You would read the file in say with TextFieldParser class line by line, place the data into a string array then write the data back to the file after finishing looping thru the file.
The replacement happens as you are reading a line that meets critiera to change text. Use IO.File.WriteAllLines to write the array back to disk.
vb Code:
dim lines() as string = io.file.readalllines("csv.txt") for x as integer = 0 to lines.getupperbound(0) if lines(x).contains(".,") then lines(x) = lines(x).replace(".", "Value4") end if next io.file.writealllines("csv.txt", lines)
thanks for the reply i will check out the links and post something if/when i figure out how to write the code.
This bit of code may not work as intended. Assuming any of value1, value2, value3 or value5 contain a ".", you would end up replacing more "."s than the one we're interested in replacing. Using indexof would most likely be a better option, depending on the input data ofc.
#EDIT: The following should work regardless of contents of the other fields (at least on the small sample of data I tried it on):
Code:Dim lines() As String = IO.File.ReadAllLines("csv.txt")
Dim i As Integer
For x As Integer = 0 To lines.GetUpperBound(0)
i = lines(x).IndexOf(".,")
If i > 0 Then
lines(x) = lines(x).Substring(0, i) & "value4" & lines(x).Substring(i + 1, lines(x).Length - i - 1)
End If
Next
IO.File.WriteAllLines("csv.txt", lines)