2011-11-03 29 views
0

我有一個CSV文件,其中有許多行需要使用VB.NET更新/替換第四列的值。列上沒有標題,因此循環可以從第一行開始。vb.net修改CSV文件中的列

infile.csv
「值1」, 「值2」, 「值3」, 「值4」

多少谷歌搜索後,有很多例子就如何讀取和寫入的CSV文件,但沒有什麼是需要的。我知道有多種方法可以完成這個任務,但是需要使用VB.NET完成。任何幫助將不勝感激。從馬可的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

我很抱歉,但我只能在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 
+0

而不是閱讀所有行,你可以使用[Textfieldparser(http://msdn.microsoft。 com/en-us/library/microsoft.visualbasic.fileio.textfieldparser.aspx)在VB.Net。但除此之外,我不知道你是否可以只編輯一個字段而不重寫整個文件 – Nicholas

+0

@Nicholas:'TextFieldParser'位於'Microsoft.VisualBasic.FileIO'命名空間內,而我提供的解決方案在每種語言中都是有效的(VB .NET,C#,ASP.NET)。解析該文件太容易需要另一個類來做,你不覺得嗎? :) – Marco

+0

@ user825315:你試過我的回答嗎?它有用嗎? – Marco