Reputation: 331
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?
Upvotes: 0
Views: 911
Reputation: 7037
Ok, that's not a big problem :) When you read your file, you get a string like "AAA\nBBB\nCCC\nDDD\nEOS\nEEE\nFFF\n...EOS\nJJJ\n..." If tou trim the string only on "EOS", you get this:
"AAA\nBBB\nCCC\nDDD\n" "\nEEE\nFFF\n..." "\nJJJ..."
Because the Split() method removes the "EOS" string, but not the new line it follows :)
string[] bags = s.Split(new string[] {"EOS\n"}, StringSplitOptions.None);
..this should work fine :)
Upvotes: 0
Reputation: 994011
Your "EOS"
separator does not contain a newline. Try:
string[] bags = s.Split(new string[] {"EOS\n"}, StringSplitOptions.None);
Your input file is
...DDDD\nEOS\nEEEE\n...
After splitting with your code, you get:
...DDDD\n EOS \nEEEE\n...
Notice the leading \n
before EEEE
. By including \n
in your separator, you will get:
...DDDD\n EOS\n EEEE\n...
Upvotes: 1