2011-12-13 96 views
0

我想在Visual Studio中創建一個Windows窗體應用程序,它可以在單擊按鈕上寫入文本文件。如何將文本文件分割爲多個其他文本文件?

我有一個txt文件(例如,test.txt的),其中包含

AAAA 
BBBB 
CCCC 
DDDD 
EOS 
FFFF 
GGGG 
HHHH 
IIII 
EOS 
JJJJ 
KKKK 
LLLL 
MMMM 
NNNN 
EOS 
EOF 

那麼我想它拆分成其他txt文件

**bag1.txt** 
AAAA 
BBBB 
CCCC 
DDDD 
EOS 

**bag2.txt** 
EEEE 
FFFF 
GGGG 
IIII 
EOS 

**bag3.txt** 
JJJJ 
KKKK 
LLLL 
MMMM 
NNNN 
EOS 
EOF 

號碼我已經寫了下面的代碼,但它只讀取源文件,直到第一個EOS:

private void filterbtn_Click(object sender, EventArgs e) 
{ 
    List<string> strFind = new List<string>(); 
    using (StreamReader sr = new StreamReader(textBox1.Text)) 
    { 
     string strIndex; 
     while((strIndex = sr.ReadLine()) != null) 
     { 
      strFind.Add(strIndex); 
      if (strIndex.Contains("EOS")) 
      { 
       break; 
      } 
     } 
    } 

    using (StreamWriter sw = new StreamWriter(@"D:\Program-program\tesfile\bag1.txt")) 
    { 
     foreach(string s in strFind) 
     { 
      sw.WriteLine(s); 
     } 

     sw.Close(); 
    } 
} 

任何人都可以告訴代碼有什麼問題嗎?

+0

我不知道你是否需要關閉()* * SW *如果你*使用*它...以防萬一 – Anton

回答

0

我覺得你有一個錯字有:

string FindEOF = strFind.Find(p => p == "EOS"); 

應該

string FindEOF = strFind.Find(p => p == "EOF"); 
+0

是的,我忘了,我不需要代碼來讀寫直到第一個EOS – Gamma

1

如果你總是使用EOS每個字符串字段的末尾嘗試是這樣的:

string s = The input text from test.txt 

string[] bags = s.Split(new string[] {"EOS"}, StringSplitOptions.None); 

// This will give you an array of strings (minus the EOS field) 
// Then write the files... 

System.IO.File.WriteAllText(bag1 path, bags[0] + "EOS"); < -- Add this you need the EOS at the end field the field 

System.IO.File.WriteAllText(bag2 path, bags[1]); 

System.IO.File.WriteAllText(bag3 path, bags[3]); 

or somthing more efficient like... 

foreach(string bag in bags) 
{ 
    ... write the bag file here 
} 
+0

爲什麼這個代碼在txt文件的第一行有bag2和bag3的空行? – Gamma

+0

有什麼方法不會失去EOS領域? – Gamma

0

以下可以得到您想要的結果。可能不是最優化的代碼,但它應該讓你在正確的方向。

static void Test() 
{      
    var allLines = File.ReadAllLines("test.txt"); 

    int controller = 0; 
    var buffer = new List<string[]>(); 

    foreach (string line in allLines) 
    { 
     string path = (controller == 0) 
      ? "bag1.txt" : (controller == 1) 
          ? "bag2.txt" : "bag3.txt"; 

     buffer.Add(new string[] { path, line }); 
     if (line == "EOS") { controller++; } 
    } 

    var fileNames = (from b in buffer select b[0]).Distinct(); 

    foreach (string file in fileNames) 
    { 
     File.WriteAllLines(file, (from b in buffer where b[0] == file select b[1]).ToArray()); 
    } 
} 

希望它有幫助!