public static byte[] GetFileData(string fileUrl) { FileStream fs = new FileStream(fileUrl, FileMode.Open, FileAccess.Read); try { byte[] buffur = new byte[fs.Length]; fs.Read(buffur, 0, (int)fs.Length); return buffur; } catch { return null; } finally { if (fs != null) { fs.Close(); } } }
public static DataTable CreateDataTableFromFile(string strFilePath) { byte[] importFile = GetFileData(strFilePath); DataTable dt = new DataTable(); var cb = new DelimitedClassBuilder("temp", ",") { IgnoreFirstLines = 0, IgnoreEmptyLines = true, Delimiter = "," }; var ms = new MemoryStream(importFile); var sr = new StreamReader(ms, Encoding.Default); var headerArray = sr.ReadLine().Split(','); foreach (var header in headerArray) { cb.AddField(header, typeof(string)); cb.LastField.FieldQuoted = true; cb.LastField.QuoteChar = '"'; } var classType = cb.CreateRecordClass(); return ReadDataTableFromStream(classType, sr); }
public static DataTable ReadDataTableFromStream(Type classType, StreamReader sr) { // Build an array of dynamic parameters var classTypes = new Type[] { classType }; // Construct our generic type var engineGenericType = typeof(FileHelperEngine<>); var engineType = engineGenericType.MakeGenericType(classTypes); var engine = Activator.CreateInstance(engineType); //return engine.ReadStream(sr) var engineReadStreamMethod = engineType.GetMethod("ReadStream", new Type[] { typeof(TextReader) }); var engineReadStreamArgs = new object[] { sr }; var engineReadStreamResult = engineReadStreamMethod.Invoke(engine, engineReadStreamArgs); //return engine.ToDataTable() var toDataTableType = typeof(FileHelpers.ExtensionsFileHelpers); var toDataTableMethod = toDataTableType.GetMethod("ToDataTable"); var toDataTableGeneric = toDataTableMethod.MakeGenericMethod(new Type[] { classType }); var toDataTableArgs = new object[] { engineReadStreamResult }; var toDataTableResult = toDataTableGeneric.Invoke(null, toDataTableArgs); return (DataTable)toDataTableResult; }
static void Main(string[] args) { string strPath = @"C:softa.txt"; DataTable dt = CreateDataTableFromFile(strPath); int intTotalCount = dt.Rows.Count; }
提示:需要引用FileHelpers控件,引用方法为:
Install-Package FileHelpers
https://stackoverflow.com/questions/4585726/readstreamasdt-filehelpers-and-c-sharp-how-do-i-dynamically-read-in-a-csv-us
https://github.com/MarcosMeli/FileHelpers/issues/273