| 將文本文件轉換為DataSet的兩種方式 摘要:本文介紹采用ODBC .NET Framework 數(shù)據(jù)提供程序和System.IO下面的FileStream、StreamReader對象來將一定格式的文本文件轉換為DataSet; 
 方式一:利用ODBC .NET Framework 數(shù)據(jù)提供程序的OdbcDataAdapter對象來填充一個DataSet ;  private DataSet GetDataset(string strFilePath)     {  if (!File.Exists(strFilePath))     {  return null;  }  string strFolderPath = Path.GetDirectoryName(strFilePath);  string strCSVFile = Path.GetFileName(strFilePath);   DataSet ds = null;  string strConnection = "Driver={Microsoft Text Driver (*.txt; *.csv)};Dbq=" + strFolderPath + ";Extensions=asc,csv,tab,txt;Persist Security Info=False";  try     {  using (OdbcConnection conn = new OdbcConnection(strConnection.Trim()))     {  conn.Open();  string strSql = "select * from [" + strCSVFile + "]";  OdbcDataAdapter odbcDAdapter = new OdbcDataAdapter(strSql, conn);  ds = new DataSet();  odbcDAdapter.Fill(ds, "table");  conn.Close();  }  return ds;  }  catch (Exception e)     {  throw e;  }  return ds;  } 方式二:利用FileStream和StreamReader讀取文件內容,手動創(chuàng)建一個DataSet;  static DataSet GetDatasetFromTxtFile(String strFilePath,String strSpilter)     {  FileStream fs = null;  StreamReader s = null;  DataSet ds = null;   try     {  fs = new FileStream(strFilePath, FileMode.Open);  s = new StreamReader(fs, System.Text.Encoding.Unicode);  ds = new DataSet();   //創(chuàng)建表  ds.Tables.Add("unicode");   //生成列  string[] columns = s.ReadLine().Split(strSpilter.ToCharArray());  foreach (string c in columns)     {  if (c.Length > 0)     {  string[] items = c.Split(strSpilter.ToCharArray());  ds.Tables["unicode"].Columns.Add(items[0]);  }  }  //生成行  string AllData = s.ReadToEnd();  string[] rows = AllData.Split("\r\n".ToCharArray());  foreach (string r in rows)     {  if (r.Length > 0)     {  string[] items = r.Split(strSpilter.ToCharArray());  ds.Tables["unicode"].Rows.Add(items);  }  }   }  catch(Exception e)     {  throw e;  }  finally     {  s.Close();  fs.Close();  }  return ds;  } 三、測試: TXT文件的格式為:(字段名和字段內容的采用逗號分開) 列名1,列名2,列名3 字段內容1,字段內容2,字段內容3 ……   測試程序,在.NET2005下通過  using System;  using System.Collections.Generic;  using System.Text;  using System.IO;  using System.Data;  using System.Data.Odbc;   namespace UnicodeTest    {  class Program     {  static void Main(string[] args)     {  //=========讀取unicode文件  String str = @"D:\unicode.txt";  String strSpilter = ",";   DataSet ds = GetDatasetFromTxtFile(str, strSpilter);   //測試輸出  DataTable dt = ds.Tables["unicode"];  String strCol = string.Empty;  foreach (DataColumn dc in dt.Columns)     {  strCol += dc.ColumnName + ("\t");  }  Console.WriteLine("{0}{1}", strCol, Environment.NewLine);  foreach (DataRow dr in dt.Rows)     {  Console.WriteLine("{0}{7}{1}{7}{2}{7}{3}{7}{4}{7}{5}{6}",  dr[0].ToString(), dr[1].ToString(), dr[2].ToString(),  dr[3].ToString(), dr[4].ToString(), dr[5].ToString(),  Environment.NewLine, "\t");   }  //======================//  }   static DataSet GetDatasetFromTxtFile(String strFilePath,String strSpilter)     {  FileStream fs = null;  StreamReader s = null;  DataSet ds = null;   try     {  fs = new FileStream(strFilePath, FileMode.Open);  s = new StreamReader(fs, System.Text.Encoding.Unicode);  ds = new DataSet();   //創(chuàng)建表  ds.Tables.Add("unicode");   //生成列  string[] columns = s.ReadLine().Split(strSpilter.ToCharArray());  foreach (string c in columns)     {  if (c.Length > 0)     {  string[] items = c.Split(strSpilter.ToCharArray());  ds.Tables["unicode"].Columns.Add(items[0]);  }  }  //生成行  string AllData = s.ReadToEnd();  string[] rows = AllData.Split("\r\n".ToCharArray());  foreach (string r in rows)     {  if (r.Length > 0)     {  string[] items = r.Split(strSpilter.ToCharArray());  ds.Tables["unicode"].Rows.Add(items);  }  }   }  catch(Exception e)     {  throw e;  }  finally     {  s.Close();  fs.Close();  }  return ds;  }   private DataSet GetDataset(string strFilePath)     {  if (!File.Exists(strFilePath))     {  return null;  }  string strFolderPath = Path.GetDirectoryName(strFilePath);  string strCSVFile = Path.GetFileName(strFilePath);   DataSet ds = null;  string strConnection = "Driver={Microsoft Text Driver (*.txt; *.csv)};Dbq=" + strFolderPath + ";Extensions=asc,csv,tab,txt;Persist Security Info=False";  try     {  using (OdbcConnection conn = new OdbcConnection(strConnection.Trim()))     {  conn.Open();  string strSql = "select * from [" + strCSVFile + "]";  OdbcDataAdapter odbcDAdapter = new OdbcDataAdapter(strSql, conn);  ds = new DataSet();  odbcDAdapter.Fill(ds, "table");  conn.Close();  }  return ds;  }  catch (Exception e)     {  throw e;  }  return ds;  }  }  }  結: 1. 如果文件不是ANSI文件格式而是Unicode格式時,采用方法一得到的是亂碼或者空字符(我的操作系統(tǒng)為中文版Server2003),而采用二可以得到更好的控制,因為我們在實例化StreamReader的時候可以指定讀取文件的編碼格式,從而可以得到我們理想的效果; 2. 得到的DataSet可以得到DataTable來進行本地的相關數(shù)據(jù)處理也可以轉換為XML或者序列化得到一個字節(jié)流來進行相關遠程處理和實時傳輸; | 
|  |