Search code examples
c#.netado.net

How to save multiple datasets into one file?


I have 2 strongly typed datasets. I need to save the containing data into single file (And of course be able to read and load them back into datasets later.). Usually I use DataSet.WriteXml() method to save the data as text and DataSet.ReadXml() to read it when I have single dataset.

The first idea that is coming to mind is to save each dataset into Memory Stream, then convert the streams to byte arrays, and then write the bytes into the file.

But this idea looks to me not very elegant or best so I was wondering if there is better way of doing it.

Any ideas? (Coded answers would be more helpful)


Solution

  • Here's some test code I wrote with LINQPad to use BinaryFormatter for multiple DataSets:

    var fsw = new FileStream(@"D:\testdataset.ser", FileMode.Create);
    var b = new BinaryFormatter();
    b.Serialize(fsw,ds);
    b.Serialize(fsw,ds2);
    fsw.Close();
    
    var fsr = new FileStream(@"D:\testdataset.ser", FileMode.Open);
    var rds = (DataSet)b.Deserialize(fsr);
    var rds2 = (DataSet)b.Deserialize(fsr);
    fsr.Close();