Datatable to string
Public static string DataTableToString (DataTable dt)
{
//! @ &, # $ %, ^ & * Is the concatenation string of the field
// To prevent the connection string from being present in the able data, write the concatenated string as a special character!
StringBuilder strData = new StringBuilder ();
StringWriter sw = new StringWriter ();
// The current data structure of the DataTable is written to the specified stream in XML format
Dt. WriteXmlSchema (sw );
StrData. Append (sw. ToString ());
Sw. Close ();
StrData. Append ("@&@");
For (int I = 0; I <dt. Rows. Count; I ++) // traverses dt Rows.
{
DataRow row = dt. Rows [I];
If (I> 0) // starts from the second row of data and adds the connection string of the row
{
StrData. Append ("# $ % ");
}
For (int j = 0; j <dt. Columns. Count; j ++) // traverses the row column
{
If (j> 0) // starts from the second field and adds the connection string of the field
{
StrData. Append ("^ &*");
}
StrData. Append (Convert. ToString (row [j]); // retrieves data
}
}
Return strData. ToString ();
}
String to Datatable
Public static DataTable StringToDataTable (string strdata)
{
If (string. IsNullOrEmpty (strdata ))
{
Return null;
}
DataTable dt = new DataTable ();
String [] strSplit = {"@&@"};
String [] strRow = {"# $ %"}; // string of the decomposed row
String [] strColumn = {"^ & *"}; // string of the decomposed Field
String [] strArr = strdata. Split (strSplit, StringSplitOptions. None );
StringReader sr = new StringReader (strArr [0]);
Dt. ReadXmlSchema (sr );
Sr. Close ();
String strTable = strArr [1]; // retrieves table data
If (! String. IsNullOrEmpty (strTable ))
{
String [] strRows = strTable. Split (strRow, StringSplitOptions. None); // parse the string array in a row
For (int rowIndex = 0; rowIndex <strRows. Length; rowIndex ++) // traverses the string array of the row
{
String vsRow = strRows [rowIndex]; // returns the string of the row.
String [] vsColumns = vsRow. Split (strColumn, StringSplitOptions. None); // parse it into a field array
Dt. Rows. Add (vsColumns );
}
}
Return dt;
}