0

I want to create a Windows Forms app in Visual Studio that writes text files on a button click.

I have a txt file (e.g. test.txt) which contains

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

Then I would like to split it into number of other txt files

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

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

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

these is the code,

private void read3btn_Click(object sender, EventArgs e)
    {
        string fileName = textBox1.Text;
        TextReader sr = new StreamReader(fileName);
          //This allows you to do one Read operation.

        string s = sr.ReadToEnd();;
        sr.Close();

        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(@"D:\Program-program\tesfile\bag1.txt", bags[0] + "EOS");  //< -- Add this you need the EOS at the end field the field

        System.IO.File.WriteAllText(@"D:\Program-program\tesfile\bag2.txt", bags[1] + "EOS");

        System.IO.File.WriteAllText(@"D:\Program-program\tesfile\bag3.txt", bags[2] + "EOS" + bags[3]);

   }}

Then the output comes this way

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

**bag2.txt**

EEEE
FFFF
GGGG
IIII
EOS

**bag3.txt**

JJJJ
KKKK
LLLL
MMMM
NNNN
EOS
EOF

unfortunately the output in bags[1] and bags[2] has a blank line in the first line, is there anyway to update the code?

4

3 回答 3

1

您的"EOS"分隔符不包含换行符。尝试:

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

您的输入文件是

...DDDD\nEOS\nEEEE\n...

与您的代码拆分后,您将获得:

...DDDD\n  EOS  \nEEEE\n...

注意前导\nEEEE通过包含\n在您的分隔符中,您将获得:

...DDDD\n  EOS\n  EEEE\n...
于 2011-12-18T18:59:39.123 回答
1

调用.Trim()以删除前导空格。

于 2011-12-18T19:00:07.390 回答
0

好的,这不是什么大问题 :) 当你阅读你的文件时,你会得到一个类似 "AAA\nBBB\nCCC\nDDD\nEOS\nEEE\nFFF\n...EOS\nJJJ\n..." 如果你仅在“EOS”上修剪字符串,您会得到:

"AAA\nBBB\nCCC\nDDD\n" "\nEEE\nFFF\n..." "\nJJJ..."

因为 Split() 方法删除了“EOS”字符串,但没有删除它后面的新行:)

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

..这应该可以正常工作:)

于 2014-06-25T08:26:07.340 回答