asp. net Realizes the method of reading data from Txt file to data view

  • 2021-07-10 19:23:47
  • OfStack

This article illustrates how asp. net can read data from an Txt file to a data view. Share it for your reference, as follows:


#region  From Txt File reads data to data view 
///  From Txt File reads data to data view 
/// </summary>
/// <param name="strExcelPath"> File path </param>
/// <returns> Return 1 Data views </returns>
public static DataView GetDataFromTxt(string strTxtPath)
{
  string strLine = "";
  DataRow row;
  try
  {
   DataTable tbl = new DataTable();
   StreamReader sr = new StreamReader(strTxtPath, Encoding.GetEncoding("GB2312"));
   strLine = sr.ReadLine(); // Read the 1 Row and column attributes 
   string[] Fields = strLine.Split(new char[] { '/t' });// Read every 1 Fields (with TAB Separate) 
   for (int k = 0; k < Fields.Length; k++) // Adding column attributes to a table 
   {
    tbl.Columns.Add(Fields[k], typeof(string));
   }
   while ((strLine = sr.ReadLine()) != null)
   {
    row = tbl.NewRow();
    string[] words = strLine.Split(new char[] { '/t' });// Read every 1 Field values (in TAB Separate) 
    for (int j = 0; j < words.Length; j++)
    {
     row[j] = words[j];
    }
    tbl.Rows.Add(row);
   }
   sr.Dispose();
   sr.Close();
   DataView dv = new DataView(tbl);
   return dv;
  }
  catch
  {
   return null;
  }
}
#endregion

I hope this article is helpful to everyone's asp. net programming.


Related articles: