Question

I've got to save a datatable to disk. It is just a single column and I've been looping round saving each row, and I've tried adding the rows to a string and then saving that.

 For i = 0 To dt.Rows.Count - 1
 fd.savefile("c:\filename.txt, " " & dt.Rows(i).Item("word"), "append")   'appends to file
 'or
 wordList = wordList & " " & dt.Rows(i).Item("word")  'builds up the word list and..
 Next
 '
 fd.saveFile("c:\filename.txt", "overwrite") 'then saves it to disk.

It is very slow.

I've found this:

http://bytes.com/topic/c-sharp/answers/250808-storing-datatable-data-hard-disk

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

That whacks out a serialized version of the data in super quick time. Much faster than my looping processes. How can I dump the datatable like that, but with no meta-data? It doesn't need to be read back into a datatable. The serialize method puts etc tags everywhere.

Était-ce utile?

La solution

Don't reopen file for each row. Either keep writng to the same stream or simply write all at once with one of File helper methods like File.WriteAllLines:

File.WriteAllLines(@"c:\filename.txt", 
    dt.Rows.OfType<DataRow>().Select(r => r.Item("word"));
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top