Click here to Skip to main content
15,903,385 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I am trying to write a File (Binary Data) into an XML file... The code can be seen below:

C#
private void FillFileData(string file)
{
                DataSet xmlFile = new DataSet("File");
    DataTable table;
    table = xmlFile.Tables.Add("Data");
    table.Columns.Add("Name",typeof(string));
    table.Columns.Add("MD5",typeof(string));
    table.Columns.Add("data",typeof(string));
    StreamReader sr = new StreamReader(file);
    table.Rows.Add(Path.GetFileName(file),"x",sr.ReadToEnd());
    sr.Close();
                xmlFile.WriteXML("test.xml");
                xmlFile.Dispose();
}

I would really appreciate any comments since i am really out of ideas here on what type should i add the Column "data" and what should i use to read the data into there...

If by any chance someone can provide info on getting the MD5 as well that would be great.
Posted
Updated 1-Mar-10 0:54am
v2

1 solution

well if you want to store binary data, you need to change the type of your column.

your md5 signature should also be changed.

you are missing your schema, so you would have to define your schema before loading your data.

So I fixed all that and rewrote your function for you, including generating the hash.

C#
private string FillFileData(string file)
{
    using (var xmlFile = new DataSet("File"))
    {
        using (var table = xmlFile.Tables.Add("Data"))
        {
            table.Columns.Add("Name", typeof(string));
            table.Columns.Add("MD5", typeof(byte[]));
            table.Columns.Add("data", typeof(byte[]));
            byte[] b = File.ReadAllBytes(file);
            var hasher = System.Security.Cryptography.MD5.Create();
            var outputHash = hasher.ComputeHash(b);
            var fileName = Path.GetFileName(file);
            var oo = new object[] { fileName, outputHash, b };
            table.Rows.Add(oo);
            string outputFileName = Path.GetTempFileName();
            using (var sw = new StreamWriter(outputFileName))
            {
                xmlFile.WriteXmlSchema(sw);
                xmlFile.WriteXml(sw);
            }
            return outputFileName;
        }
    }
}
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900