2012-07-19 85 views
0

我有一個1000 000記錄的文本文件,所以我想將文件分割成將有100記錄每個多個文件。這是我使用listbox1控制文件的代碼。代碼正在工作,但缺少記錄。拆分一個文本文件轉換成更小的文件

private void WriteToFile() 
    { 
     int RowCount = listBox1.Items.Count; 
     string FileName = "C:\\Users\\bbdnet0986\\Documents\\MyExpotedQADATA"; 
     StreamWriter sw = new StreamWriter(FileName + ".txt"); 
     int inc = 0; 
     int counter = 0; 
     //StreamWriter sw = new StreamWriter(FileName+inc + ".txt"); 
     for (int i = 0; i < listBox1.Items.Count; i++) 
     { 
      sw.WriteLine(listBox1.Items[i].ToString()); 
      string me = listBox1.Items[i].ToString(); 

      if (RowCount > 100) 
      { 

       listBox2.Items.Add(listBox1.Items[counter].ToString()); 
       counter++; 
       if (counter == 100) 
       { 

        inc++; 
        sw = new StreamWriter(FileName + inc + ".txt"); 


        RowCount = RowCount - counter; 
        counter = 0; 

       } 
      } 

      else 
      { 
        sw.WriteLine(listBox1.Items[i].ToString()); 
      } 

     } 
     sw.Close(); 
    } 
+2

什麼是你的問題? – jrummell 2012-07-19 12:28:26

+0

ListBox不太適合或打算容納1M項目。 – 2012-07-19 12:32:39

回答

0

在這一行:

sw = new StreamWriter(FileName + inc + ".txt"); 

你需要.Flush()之前的SW。作者被緩衝,這就是爲什麼有些記錄丟失。

0

我不知道你的問題是如何與你的ListBox,所以我會告訴你,從每次100線一個巨大的文件創建文件的解決方案。

它很容易與LinqEnumerable.GroupBy

int maxLineCount = 100; 
FileInfo file = new FileInfo(hugeFilePath); 

var fileGroups = File.ReadLines(file.FullName) 
    .Select((l, i) => new { Line = l, Index = i }) 
    .GroupBy(x => x.Index/maxLineCount) 
    .Select(grp => new { FileIndex = grp.Key, Lines = grp.Select(x => x.Line)}); 

foreach (var grp in fileGroups) 
{ 
    var fileName = "File" + grp.FileIndex; 
    var path = Path.Combine(@"C:\Temp\Test", fileName + file.Extension).ToString(); 
    File.WriteAllLines(path, grp.Lines); 
} 

注意File.ReadLines流線,而不是裝載所有到內存中。

0

這裏有一個更簡單的方法:

private void WriteToFile() 
{ 
    // get an array of strings - you'll find out way :) 
    string[] items = listBox1.Items.Cast<string>().ToArray(); 

    // this would also work with ReadAllLines() 
    string[] items = File.ReadAllLines("Your original file"); 

    // path + filename prefix 
    string fileNamePattern = "C:\\Users\\bbdnet0986\\Documents\\MyExpotedQADATA{0}.txt"; 

    // blocks of 100 
    string[] buffer; 
    for(int i = 0; i < items.Length; i += 100) 
    { 
     // slice the string array into 100 string blocks 
     buffer = items.Slice(i, 100); 

     // output the block of strings 
     File.WriteAllLines(string.Format(fileNamePattern, i), buffer); 
    } 
} 

片段擴展:

public static T[] Slice<T>(this T[] source, int index, int length) 
    { 
     T[] slice = new T[length]; 
     Array.Copy(source, index, slice, 0, length); 
     return slice; 
    } 
+0

這會不必要地一次將1000000行加載到內存中。 – 2012-07-20 08:19:38

+0

@TimSchmelter - 因爲你已經把最好的答案另一種方法。另外請注意,我的解決方案比LINQ速度更快,.NET 2.0-3.5(VS 2008中)友好的:)不過,我想我可以用一個FileStream代替。 – 2012-07-20 12:24:24