how can i write a byte array to a file using a SaveFileDialog?

10,095

Solution 1

You say you've got the bytes "manually entered via a richtextbox" - but you're just getting the ASCII-encoded value of the text. If you were expecting that to (say) parse hex, then you'll be disappointed. It's not really clear what you're trying to do, but if you are trying to save text, you don't need to convert it into a byte array yourself.

Next, you're currently writing to a MemoryStream, so it's clearly not going to save to a file... if you really wanted to do this, you should use a FileStream instead (either constructed directly or via File.OpenWrite etc). However, you don't need to do all that work yourself...

The simplest way to save a bunch of bytes is:

File.WriteAllBytes(file.FileName, bytes);

The simplest way to save a string is:

File.WriteAllText(file.FileName, text); // Optionally specify an encoding too

Solution 2

you can do that simply by using File.WriteAllText method:

    SaveFileDialog file = new SaveFileDialog();
    file.ShowDialog();

    if (file.FileName != "")
    {
        File.WriteAllText(file.FileName, richTextBox1.Text);
    }
Share:
10,095
Mein Luck
Author by

Mein Luck

Updated on June 05, 2022

Comments

  • Mein Luck
    Mein Luck almost 2 years

    Basically I have have a program that creates an array of bytes (manually entered via a richtextbox and I want to be able to create a new file and save the bytes in that file via a SaveFileDialog() method.

    The code I have come up with is:

    byte[] bytes = Encoding.ASCII.GetBytes(richTextBox1.Text);
    Stream stream = new MemoryStream(bytes);
    
    SaveFileDialog file = new SaveFileDialog();
    file.ShowDialog();
    
         if (file.FileName != "")
         {
             using (BinaryWriter bw = new BinaryWriter(stream)) 
             {
                 bw.Write(bytes); 
             }
    
    
         }