如何将文本文件分割为多个其他文本文件?
问题描述:
我想在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();
}
}
任何人都可以告诉代码有什么问题吗?
答
我觉得你有一个错字有:
string FindEOF = strFind.Find(p => p == "EOS");
应该
string FindEOF = strFind.Find(p => p == "EOF");
+0
是的,我忘了,我不需要代码来读写直到第一个EOS – Gamma
答
如果你总是使用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
}
答
以下可以得到您想要的结果。可能不是最优化的代码,但它应该让你在正确的方向。
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());
}
}
希望它有帮助!
我不知道你是否需要关闭()* * SW *如果你*使用*它...以防万一 – Anton