SaiBand
SaiBand

Reputation: 5355

Generate Binary Contents of an XML File

I have a column called contents in a table called File in SQL Server 2008. The content column's data type is varbinary(MAX). I have an XML file and I need to generate its content in binary using c#.net 3.5.

The name of the file is Test.XML and I need to generate its contents in a file called Test.txt. Then I can write a update script to set its contents.

Upvotes: 0

Views: 4419

Answers (1)

jcvandan
jcvandan

Reputation: 14324

Open the file, convert to a byte array, then just stick the byte array into the varbinary field in your db:

string xml = File.ReadAllText("text.xml");
byte[] bytes = Encoding.ASCII.GetBytes(xml);

// put bytes into db

UPDATE:

If you really do want it as a string representation of 0's and 1's - pointless as that seems to me, you just need iterate through the byte array and convert each byte to base 2 binary and add said value to a string builder object like this:

string xml = File.ReadAllText("text.xml");
byte[] bytes = Encoding.ASCII.GetBytes(xml);
StringBuilder sb = new StringBuilder();

foreach (byte b in bytes)
{
    sb.Append(Convert.ToString(b, 2));
}

File.WriteAllText("test2.txt", sb.ToString());

I don't want anyone to vote me down for this seemingly silly answer - look at the comments below this is what he says he wants.

UPDATE:

To convert the byte array to hex do the following:

string xml = File.ReadAllText("text.xml");
byte[] bytes = Encoding.ASCII.GetBytes(xml);
StringBuilder sb = new StringBuilder();

foreach (byte b in bytes)
{
      sb.AppendFormat("{0:x2}", b);
}

File.WriteAllText("test2.txt", sb.ToString());

Upvotes: 1

Related Questions