如何将文本文件拆分为多个其他文本文件?

时间:2011-12-13 12:30:09

标签: c# streamreader streamwriter

我想在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();
    }
}

有人能说出代码有什么问题吗?

3 个答案:

答案 0 :(得分: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
}

答案 1 :(得分:0)

我认为你有一个错字:

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

应该是

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

答案 2 :(得分: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());
    }
}

希望它有所帮助!