function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
ManoharSFManoharSF 

convert file to base64Binary in C#

Hi there,

Has anyone encoded a file into base64binary in C#? I have requirement to attach a file to leads through a external site.

 

Has anyone got experience in this, if so can you please share?

 

Thanks

Manohar

Keyur PatelKeyur Patel

Hi,

 

Please find the following code for convert file to base64Binary in C#.

 

private void btnEncode_Click(object sender, EventArgs e)

{

  if (!string.IsNullOrEmpty(txtInFile.Text))

  {

    FileStream fs = new FileStream(txtInFile.Text,

                                   FileMode.Open,

                                   FileAccess.Read);

    byte[] filebytes = new byte[fs.Length];

    fs.Read(filebytes, 0, Convert.ToInt32(fs.Length));

    string encodedData =

        Convert.ToBase64String(filebytes,                

                               Base64FormattingOptions.InsertLineBreaks);

    txtEncoded.Text = encodedData;

  }

}

 

private void btnDecode_Click(object sender, EventArgs e)

{

  if (!string.IsNullOrEmpty(txtOutFile.Text))

  {

    byte[] filebytes = Convert.FromBase64String(txtEncoded.Text);

    FileStream fs = new FileStream(txtOutFile.Text,

                                   FileMode.CreateNew,

                                  FileAccess.Write,

                                   FileShare.None);

    fs.Write(filebytes, 0, filebytes.Length);

    fs.Close();

  }

}

 

Please find also following link

http://ozgur.ozcitak.com/snippets/2009/12/21/base64-encoding-an-image-with-csharp.html

 

Regards,

Keyur Patel