0

Code:

private void btnSaveFile_Click(object sender, EventArgs e)
{
    listBox1.MultiColumn = true;
    SaveFileDialog sfd = new SaveFileDialog();
    sfd.Filter = "Text File|*.txt";
    if (sfd.ShowDialog() == DialogResult.OK) ;
    {
        string path = sfd.FileName;
        BinaryWriter bw = new BinaryWriter(File.Create(path));
        foreach (string s in hello)
        {
            bw.Write(s + Environment.NewLine);
        }
    }

output for

this

I really don't know how to get rid of those characters.

abatishchev
  • 98,240
  • 88
  • 296
  • 433

2 Answers2

3

If you want to write to a text file do not use a BinaryWriter. It appends the length of the string which explains why you are observing those strange characters.

You could use TextWriter:

using (var fileStream = File.Create(path)
using (var writer = new StreamWriter(fileStream))
{
    foreach (string s in hello) 
    {
        writer.Write(s + Environment.NewLine);
    }
}

or in this particular example you could shorten all this code to a single line of code using the WriteAllLines method:

if (sfd.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
    string path = sfd.FileName;
    File.WriteAllLines(path, hello);
}

Also be careful! You have a trailing ; after your if statement. This means that the write to the file will always happen, no matter whether the user confirmed or canceled the file dialog. Notice how I removed it in my last example.

Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
  • To add, a `BinaryWriter` appends the length (7-bit encoded binary form) of the string before writing the string. That's what causing the problem – Alvin Wong Jan 18 '13 at 06:39
0

try:

StreamWriter sw = new StreamWriter(path);

StreamWriter is very ideal for writing text in files. While BinaryWriter writes primitive types in binary to a stream and supports writing strings in a specific encoding.

abatishchev
  • 98,240
  • 88
  • 296
  • 433
triksma
  • 43
  • 6