Storing datatable data in hard disk

  • Thread starter Thread starter VMI
  • Start date Start date
V

VMI

Is it possible to store the data in a datatable in the hard disk instead of
the memory? By default, when a datatable's being filled, the table (and
data) will remain in memory. Would it be possible to save this data in
another medium besides the memory? Everything would stay the same but
instead of filling up the datatable by storing it in the memory, i'd be
storing it somewhere in the hard drive.

Thanks.
 
VMI said:
Is it possible to store the data in a datatable in the hard disk instead of
the memory? By default, when a datatable's being filled, the table (and
data) will remain in memory. Would it be possible to save this data in
another medium besides the memory? Everything would stay the same but
instead of filling up the datatable by storing it in the memory, i'd be
storing it somewhere in the hard drive.

System.Data.DataTable implements ISerializable, so this is no big
challenge: the following example uses binary serialization

using System.Runtime.Serialization.Formatters.Binary;

[...]

//Create DataTable and Serialize
private void button1_Click(object sender, System.EventArgs e)
{
DataTable dt = new DataTable();
dt.Columns.Add("uid");
dt.Columns.Add("test");
for (int i = 0; i < 10; i++)
{
DataRow dr = dt.NewRow();
dr[0] = i;
dr[1] = string.Format("test{0}", i);
dt.Rows.Add(dr);
}

FileStream fs = new FileStream(@"C:\test.bin", FileMode.Create);
BinaryFormatter bf = new BinaryFormatter();
bf.Serialize(fs, dt);
fs.Close();
}


//Deserialize DataTable from File
private void button2_Click(object sender, System.EventArgs e)
{
FileStream fs = new FileStream(@"C:\test.bin", FileMode.Open);
BinaryFormatter bf = new BinaryFormatter();
DataTable dt = (DataTable) bf.Deserialize(fs);
fs.Close();
foreach (DataRow dr in dt.Rows)
{
Debug.WriteLine(dr[0].ToString());
}
}

There are also possibilities to serialize data to XML/SOAP, have a look
at the documentation:

http://msdn.microsoft.com/library/en-us/cpguide/html/cpovrSerializingObjects.asp

Cheers

Arne Janning
 
Back
Top