Ask the Expert

Enabling the storage of an audio file in a XML file

Is there any way to enable the storage of an audio file in a XML file?
Yes, you can store binary data in XML documents. Because of the special characters that are needed by XML, it is necessary to encode the binary data using either the Base64 encoding algorithm, or the hexadecimal encoding algorithm. Read more on this from MSDN here:
http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dnwebsrv/html/infoset_whitepaper.asp

The System.Convert class contains methods for helping you convert between Base64 and non-Base64 data. Refer to the System.Convert.ToBase64String() and System.Convert.FromBase64String() methods for more information in the MSDN Library.

Here is an example method of how you might read the file in and convert it to a Base64 encoded string. Note that this method is just for demo purposes and I would not recommend reading the entire file in at once like this method is going to show. Read it in segments or asynchronously but never all at once.

 using System;
 using System.Diagnostics;
 using System.IO;
 
 namespace Base64Example
 {
  /// <summary>
  /// Summary description for Base64Encoder.
  /// </summary>
  public class Base64
  {
   /// <summary>
   /// Read the file into a base 64 string (Not an efficient means, just used for demonstration purposes!)
   /// </summary>
   /// <param name="path">The name of the file to read</param>
   /// <returns></returns>
   public static string ReadFile(string path)
   {
    string base64String = string.Empty;
    try
    {
     FileStream fs = File.Open(path, FileMode.Open, FileAccess.Read);
     if (fs != null)
     {
      byte[] bytes = new byte[fs.Length];
      int bytesRead = fs.Read(bytes, 0, (int)fs.Length);
      if (bytesRead > 0)
      {
       base64String = System.Convert.ToBase64String(bytes);
      }
     }
    }
    catch(Exception ex)
    {
     Trace.WriteLine(ex);
    }
    return base64String;
   }
 
  }
 }
 
Reversing the process should be trivial. Simply take the string and use the FromBase64String method to convert it back to it's original byte[]. Once converted, write it back out to your file.

Cheers,
Mark

This was first published in August 2004

There are Comments. Add yours.

 
TIP: Want to include a code block in your comment? Use <pre> or <code> tags around the desired text. Ex: <code>insert code</code>

REGISTER or login:

Forgot Password?
By submitting you agree to receive email from TechTarget and its partners. If you reside outside of the United States, you consent to having your personal data transferred to and processed in the United States. Privacy
Sort by: OldestNewest

Forgot Password?

No problem! Submit your e-mail address below. We'll send you an email containing your password.

Your password has been sent to: