Extension Methods for Easy Data Extraction
Today I am continuing the theme of extension methods by talking about a few I primarily use for aiding in testing scenarios. Have you ever been in the situation where you are stepping through your code and get a set of data back from a SQL call and wish there was an easy way to save it so you could use it as test data? I have a few extension methods that make this situation much easier and all deal with a DataTable.
DataTable Extension Methods
public static void ToCSVFile(this DataTable dt, string fileName, char splitCharacter) { File.WriteAllText(fileName, dt.ToCSVString(splitCharacter)); } public static string ToCSVString(this DataTable dt, char splitCharacter) { StringBuilder sb = new StringBuilder(); string[] columnNames = dt.Columns.Cast<DataColumn>(). Select(column => column.ColumnName). ToArray(); sb.AppendLine(string.Join(",", columnNames)); foreach (DataRow row in dt.Rows) { string[] fields = row.ItemArray.Select(field => field.ToString()).ToArray(); sb.AppendLine(string.Join(",", fields)); } return sb.ToString(); } public static void FromCSVFile(this DataTable dt, string fileName, char splitCharacter) { StreamReader sr = new StreamReader(fileName); dt.FromCSVString(sr.ReadToEnd(), splitCharacter); } public static void FromCSVString(this DataTable dt, string csvData, char splitCharacter) { StringReader sr = new StringReader(csvData); string[] columns; string[] rows; string myStringRow = sr.ReadLine(); columns = myStringRow.Split(splitCharacter); foreach (string column in columns) { dt.Columns.Add(column); } myStringRow = sr.ReadLine(); while (myStringRow != null) { rows = myStringRow.Split(splitCharacter); dt.Rows.Add(rows); myStringRow = sr.ReadLine(); } }
Here I have four extension methods that make saving and loading a DataTable extremely easy. You can save to and read from a file or string that contains data separated by the delimiter of your choosing.
Usage
There are two ways to use these methods to save data off quickly, of course these methods can also be used for normal coding as well and not limited to the below scenarios.
- Drop in a line of code right after you get the data back into your DataTable.
myTable.ToCSVFile(@"C:\Source\CSVTest.csv", ','); // OR string s = myTable.ToCSVString(',');
- While debugging use the Immediate Window and write the same line after a break point … Continue reading