我有一个包含许多行的CSV文件,我需要使用VB.NET更新/替换第四列的值。列上没有标题,因此循环可以从第一行开始。
infile.csv
"值1""值2""值3"" VALUE4"
经过大量的谷歌搜索,有很多关于如何读取和写入CSV文件的例子,但没有一个完全需要。我知道有多种方法可以完成这项任务,但要求是用VB.NET完成的。任何帮助将不胜感激。
最终代码来自Marco的C#回答
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())
答案 0 :(得分:0)
对不起,我只能用C#写它 我想你不会发现很多转换为VB.NET的问题 这是我的代码:
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版本:
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