2014-01-21 28 views
1

內容內容的新文件如下:過濾CSV文件,並創建一個基於原始文件DOC.csv原

AH08B/001319;F09351812;F09351812;F09351812;20131112;101009;10;3.30;15.00;0 
AH08B/001319;F09351812;F09351812;F09351812;20131112;101009;10;3.30;15.00;0 
AH08B/001320;F09351812;F09351812;F09351812;20131112;101271;400;1.30;5.00;10 

第一列篩選該文件,我需要獲得兩個新文件:

文件1

AH08B/001319;F09351812;F09351812;F09351812;20131112;101009;10;3.30;15.00;0 
AH08B/001319;F09351812;F09351812;F09351812;20131112;101009;10;3.30;15.00;0 

文件2

AH08B/001320;F09351812;F09351812;F09351812;20131112;101271;400;1.30;5.00;10 

我可以遵循以獲得這些結果的最佳方法是什麼?

+0

哪個元素決定文件1或文件2?有多個候選項出現 – Plutonix

+0

我按第一列過濾,其中包含「AH08B/0013XX」 –

+0

我將使用LINQTOXML創建兩個子列表http://www.dotnetcurry.com/showarticle.aspx?ID=564 – CheGueVerra

回答

2

只要文件不是太大,無法在內存中,這樣的事情應該工作:

Dim groups = IO.File.ReadAllLines("DOC.csv").GroupBy(Function(x) x.Substring(0, x.IndexOf(";"c))) 
For i = 0 To groups.Count - 1 
    IO.File.WriteAllLines("DOC" & (i + 1).ToString.PadLeft(2, "0"c) & ".csv", groups(i).ToArray) 
Next 

如果內存這裏的問題是,將工作的一種方式:

Dim keys As New List(Of String) 
Using sr As New IO.StreamReader("textfile1.txt") 
    Do Until sr.EndOfStream 
     Dim line = sr.ReadLine 
     Dim key As String = line.Substring(0, line.IndexOf(";"c)) 
     If keys.Contains(key) Then 
      IO.File.AppendAllText("DOC" & (keys.IndexOf(key) + 1).ToString.PadLeft(2, "0"c) & ".csv", line & vbNewLine) 
     Else 
      keys.Add(key) 
      IO.File.WriteAllText("DOC" & keys.Count.ToString.PadLeft(2, "0"c) & ".csv", line & vbNewLine) 
     End If 
    Loop 
End Using 

無論採用哪種方式,都會根據第一個字段和「DOCxx.csv」格式的文件名創建文件。

1

下面是您的csv文件的第一個元素,創建一個新文件(如果不存在),然後將記錄添加到它。這一行一行一行地處理(例如,未針對速度進行優化),但不應該遇到內存限制。

string fileName = "C:\\Temp\\T1.csv"; 
if (File.Exists(fileName)) 
{ 
    StreamReader sr = new StreamReader(fileName); 
    while (!sr.EndOfStream) 
    { 
     string record = sr.ReadLine(); 
     string newFileName = "C:\\Temp\\" + record.Substring(0, record.IndexOf(";")) + ".csv"; 
     if (!File.Exists(newFileName)) 
     { 
      File.Create(newFileName); 
     } 
     StreamWriter sw = new StreamWriter(newFileName, true); 
     sw.WriteLine(record); 
     sw.Close(); 
    } 
    sr.Close(); 
} 
+0

初始化StreamWriter時只有一個警告:在mscorlib.dll中發生未處理的類型爲「System.IO.IOException」的異常其他信息:進程無法訪問文件'c:\ temp \ doc3.csv',因爲它正在被使用通過另一個進程。 –

相關問題