I have a CSV file with many rows in which I need to update/replace column four's value using VB.NET. There are no headers on the columns so the loop can start on row one.
infile.csv
"value1","value2","value3","value4"
After much googling, there are lots of examples on how to read and write CSV files, but none quite what is needed. I know there are multiple ways to accomplish this task, but a requirement is that it's done with VB.NET. Any help would be greatly appreciated.
Final code ported from Marco's C# answer
Private Sub CSVmod(ByVal strFileName As String, ByVal newFileName As String)
Dim strLines As String() = File.ReadAllLines(strFileName)
Dim strList As New List(Of String)
Dim strReplace As String = "test"
For Each line In strLines
Dim strValues As String() = line.Split(",")
If (strValues.Length = 14) Then
strValues(3) = strReplace
strList.Add(String.Join(",", strValues))
End If
Next
File.WriteAllLines(newFileName, strList.ToArray())
I'm sorry, but I can write it only in C#.
I think you won't find many problems to convert to VB.NET.
Here is my code:
private void SubstFile(string filename, string newFileName)
{
// Reading all rows of the file
string[] lines = File.ReadAllLines(filename);
List<string> list = new List<string>();
foreach (string line in lines)
{
// For every row I split it with commas
string[] values = line.Split(',');
// Check to have 4 values
if (values.Length == 4)
{
// Substitute fourth value
values[3] = "new value";
// Add modified row to list
list.Add(String.Join(",", values));
}
}
// Save list to new file
File.WriteAllLines(newFileName, list.ToArray());
}
VB.NET version:
Private Sub SubstFile(filename As String, newFileName As String)
' Reading all rows of the file
Dim lines As String() = File.ReadAllLines(filename)
Dim list As List(Of String) = New List(Of String)()
For Each line As String In lines
' For every row I split it with commas
Dim values As String() = line.Split(","c)
' Check to have 4 values
If values.Length = 4 Then
' Substitute fourth value
values(3) = "new value"
' Add modified row to list
list.Add(String.Join(",", values))
End If
Next
' Save list to new file
File.WriteAllLines(newFileName, list.ToArray())
End Sub
Use python....one line of code
df = pandas.read_csv('file.csv)
Related
I have a config file which contain multiple lines.
DataBaseType =1
ServerName=LAPTOP-XXXX
Database=mydatabase
Connection Timeout=3000
User ID=sa
Password=sasa
ServerIp=xxxx:8083
ServiceType=http://
Backup Driver=D:\
Backup Folder=SWBACKUP
Database Restore=D:\
Now I want to generate a string which will be a sqlconnection string by reading,splitting and joining texts. it should be
"Data Source=LAPTOP-XXXX;Initial Catalog=mydatabase;User ID=sa;Password=sasa"
I am able to read text using streamreader , but I am not able to split and join those texts.
You can create a method that converts your config file to a Dictionary(Of String, String) and then get the values as needed.
Take a look at this example:
Private Function ReadConfigFile(path As String) As Dictionary(Of String, String)
If (String.IsNullOrWhiteSpace(path)) Then
Throw New ArgumentNullException("path")
End If
If (Not IO.File.Exists(path)) Then
Throw New ArgumentException("The file does not exist.")
End If
Dim config = New Dictionary(Of String, String)
Dim lines = IO.File.ReadAllLines(path)
For Each line In lines
Dim separator = line.IndexOf("=")
If (separator < 0 OrElse separator = line.Length - 1) Then
Throw New Exception("The following line is not in a valid format: " & line)
End If
Dim key = line.Substring(0, separator)
Dim value = line.Substring(separator + 1)
config.Add(key, value)
Next
Return config
End Function
Example: Live Demo
What this Function does is:
Make sure that a path was given
Make sure that the file exists as the given path
Loop over each line
Make sure that the line is in the correct format (key=value)
Append the Key/Value to the Dictionary
you can use readline method, then make something as follow for database line:
Dim reader As New StreamReader(filetoimport.Txt, Encoding.Default)
Dim strLine As String
Do
' Use ReadLine to read from your file line by line
strLine = reader.ReadLine
Dim retString As String
'to get the string from position 0 length 8
retString = strLine .Substring(0, 8)
'check if match
if retString ="Database" Then
Dim valueString As String
valueString = strLine .Substring(9, strLine.length)
...
Loop Until strLine Is Nothing
I am using Visual Basic.net.
If I have a string that has many lines in it, is it possible to insert a string at a certain line? I see that there is an insert function for strings. Is there a function to insert a string at a certain line of another string?
Is there a function to insert a string at a certain line of another
string?
No, because a string is not a list/array of lines. You have to split it by Environment.NewLine to get an array, ToList to get a List(Of String) which has an Insert method. Then you can use String.Join to put it together after you have inserted it:
Dim lines = MultiLineText.Split({Environment.NewLine}, StringSplitOptions.None).ToList()
lines.Insert(2, "test") ' will throw an ArgumentOutOfRangeException if there are less than 2 lines '
Dim result = String.Join(Environment.NewLine, lines)
There is no string methods that handles a string as a collections of lines. You can use the Insert method, but you have to find out where in the string to put the line yourself.
Example:
' Where to insert
Dim line As Integer = 4
' What to insert
Dim content As String = "asdf"
' Locate the start of the line
Dim pos As Integer = 0
Dim breakLen As Integer = Environment.Newline.Length
For i As Integer = 0 to line
pos = text.IndexOf(Environment.Newline, pos + breakLen)
Next
' Insert the line
text = text.Insert(pos, content + Environment.Newline)
Strings have no idea what a "line" is. A string is only a sequence of characters. What you can do is to convert your string into a list of individual lines (for example as List<string>) and then insert into that list.
List<string> listOfLines = new List<string>();
listOfLines.AddRange(sourceString.Split(new String[] { Environment.NewLine }, StringSplitOptions.None));
listOfLines.Insert(13, "I'm new here");
string result = String.Join(Environment.NewLine, listOfLines);
This is C# code, but I'm pretty sure you can easily convert this to VB.NET.
I have a text file contains delimited records.
1243;jhhf';982u4k;9u2349;huf8
kij;9238u;98ur23;jfwf;03i24
I need to replace the value of 4th part from every record with the value returned from database or someother source.
Any clue ? expecting VB CODE
Take a look at here( for C# language );
Split string in C#
You could try this (written in C#):
C# release
List<string> newLines = new List<string>();
string[] lines = File.ReadAllLines(filename);
foreach (string line in lines)
{
string[] parts = line.Split(";".ToCharArray());
parts[3] = string_from_db;
newLines.Add(String.Join(";", parts));
}
File.WriteAllLines(filename, newLines.ToArray());
VB.NET release
Dim newLines As List(Of String) = New List(Of String)
Dim lines As String() = File.ReadAllLines(filename)
For Each line As String In lines
Dim parts As String() = line.Split(";")
parts(3) = string_from_db
newLines.Add(String.Join(";", parts))
Next
File.WriteAllLines(filename, newLines.ToArray())
I have a string like
Query_1,ab563372363_C/R,100.00,249,0,0,1,249,1,249,1e-132, 460
Query_1,ab563372356_C/R,99.60,249,1,0,1,249,1,249,5e-131, 455
in a file
in two separate lines. I am reading it from the textbox. I have to output ab563372363_C/R and ab563372356_C/R in a text box. I am trying to use the split function for that but its not working..
Dim splitString as Array
results = "test.txt"
Dim FileText As String = IO.File.ReadAllText(results) 'reads the above contents from file
splitString = Split(FileText, ",", 14)
TextBox2.text = splitString(1) & splitString(13)
for the above code, it just prints the whole thing.. What's wrong?
Try this
Private Function GetRequiredText() As List(Of String)
Dim requiredStringList As New List(Of String)
Dim file = "test.txt"
If FileIO.FileSystem.FileExists(file) Then
Dim reader As System.IO.StreamReader = System.IO.File.OpenText(file)
Dim line As String = reader.ReadLine()
While line IsNot Nothing
requiredStringList.Add(line.Split(",")(1))
line = reader.ReadLine()
End While
reader.Close()
reader.Dispose()
End If
Return requiredStringList
End Function
This will read the file line by line and add the item you require to a list of strings which will be returned by the function.
Returning a List(Of String) may be overkill, but it's quite simple to illustrate and to work with.
You can then iterate through the list and do what you need with the contents of the list.
Comments welcome!!
Also this might work...
Dim query = From lines In System.IO.File.ReadAllLines(file) _
Select lines.Split(",")(1)
this will return an IEnumerable(Of String)
Enjoy
First
Since you are reading the whole text, your FileText would be ending like this:
Query_1,ab563372363_C/R,100.00,249,0,0,1,249,1,249,1e-132,460
\r\n
Query_1,ab563372356_C/R,99.60,249,1,0,1,249,1,249,5e-131, 455
So when you are referencing to your splitStringwith those indexes (1, 13) your result might probably be wrong.
Second
Try to specify what kind of type your array is, Dim splitString as Array should be Dim splitString As String()
Third
Make your code more readable/maintainable and easy to edit (not only for you, but others)
The Code
Private const FirstIndex = 1
Private const SecondIndex = 12
Sub Main
Dim myDelimiter As Char
Dim myString As String
Dim mySplit As String()
Dim myResult1 As String
Dim myResult2 As String
myDelimiter = ","
myString += "Query_1,ab563372363_C/R,100.00,249,0,0,1,249,1,249,1e-132, 460"
myString += "Query_1,ab563372356_C/R,99.60,249,1,0,1,249,1,249,5e-131, 455"
mySplit = myString.Split(myDelimiter)
myResult1 = mySplit(FirstIndex)
myResult2 = mySplit(SecondIndex)
Console.WriteLine(myResult1)
Console.WriteLine(myResult2)
End Sub
I'm working on a project that requires me to take values from a CSV file. I've to do further processing with these values and it'd be great if I can have these values in a 2D array. The number of rows and columns of the CSV files changes at regular intervals.
I'm unable to take these values into a 2D array in VB.NET/C#. Can I please have some help on that?
Here the code that I used:
Imports System.IO
Public Class Form1
Private Sub ReadCSVFileToArray()
Dim strfilename As String
Dim num_rows As Long
Dim num_cols As Long
Dim x As Integer
Dim y As Integer
Dim strarray(1, 1) As String
' Load the file.
strfilename = "test.csv"
'Check if file exist
If File.Exists(strfilename) Then
Dim tmpstream As StreamReader = File.OpenText(strfilename)
Dim strlines() As String
Dim strline() As String
strlines = tmpstream.ReadToEnd().Split(Environment.NewLine)
' Redimension the array.
num_rows = UBound(strlines)
strline = strlines(0).Split(",")
num_cols = UBound(strline)
ReDim strarray(num_rows, num_cols)
' Copy the data into the array.
For x = 0 To num_rows
strline = strlines(x).Split(",")
For y = 0 To num_cols
strarray(x, y) = strline(y)
Next
Next
' Display the data in textbox
For x = 0 To num_rows
For y = 0 To num_cols
TextBox1.Text = TextBox1.Text & strarray(x, y) & ","
Next
TextBox1.Text = TextBox1.Text & Environment.NewLine
Next
End If
End Sub
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
ReadCSVFileToArray()
End Sub
End Class
You use the CsvReader from here to easily and conveniently read a csv (or other similar data) into a DataTable (or an IDataReader). It is always my first choice for this scenario - fast and pretty robust.
I'm not disagreeing with Marc Gravell, because you shouldn't try to re-invent the wheel. His solution would perform the best, and there can be many CSV format nuances that can screw up a simple parser such as the one demonstrated below.
With that said, you asked for a CSV parser that returns a 2D array. The code below does just that (jagged array), and should work for a very simple CSV file. This skips a header row in the file.
(sorry it's not in VB, but you can put it in a helper class in your project)
private string[][] GetData(string fileName)
{
List<string[]> data = new List<string[]>();
using (StreamReader sr = new StreamReader(fileName))
{
bool headerRow = true;
string line;
while ((line = sr.ReadLine()) != null)
{
if (headerRow)
{
headerRow = false;
}
else
{
string[] split = line.Split(new char[] { ',' });
data.Add(split);
}
}
}
return data.ToArray();
}
Parsing a CSV file can be pretty hard due to all the possible variations of CSV. See: http://en.wikipedia.org/wiki/Comma-separated_values
E.g., think about embedded quotes, commas etc.
So it will not be a simple matter of reading lines/strings and splitting them.
Perhaps you are better of by using a third party library
Since the number of columns and rows change frequently, you could use dynamic lists rather than a fixed 2D array.
List<List<string>> data = new List<List<string>>();
Then as you parse the CSV file you can build up the data dynamically in the above structure, adding a new List<string> to data for each new row in the CSV file.
Update: The VB.NET equivalent is something like
data As New List(Of List(Of String))
That being said, #Mark Gravell's suggestion is a far better solution than doing this yourself.