■ OleDbConnection 클래스를 사용해 CSV 파일을 로드하는 방법을 보여준다.
▶ Program.cs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 |
using System; using System.Data; using System.Data.OleDb; using System.Globalization; using System.IO; using System.Reflection; namespace TestProject { /// <summary> /// 프로그램 /// </summary> class Program { //////////////////////////////////////////////////////////////////////////////////////////////////// Method ////////////////////////////////////////////////////////////////////////////////////////// Static //////////////////////////////////////////////////////////////////////////////// Private #region 데이터 테이블 구하기 - GetDataTable(csvFilePath, useFirstRowHeader) /// <summary> /// 데이터 테이블 구하기 /// </summary> /// <param name="csvFilePath">CSV 파일 경로</param> /// <param name="useFirstRowHeader">첫번째 행 헤더 사용 여부</param> /// <returns>데이터 테이블</returns> private static DataTable GetDataTable(string csvFilePath, bool useFirstRowHeader) { string headerFlag = useFirstRowHeader ? "Yes" : "No"; string directoryPath = Path.GetDirectoryName(csvFilePath); string fileName = Path.GetFileName(csvFilePath); string sql = $"SELECT * FROM [{fileName}]"; string connectionString = $"Provider=Microsoft.Jet.OleDb.4.0; Data Source={directoryPath};Extended Properties=\"Text;HDR={headerFlag};FMT=Delimited\""; using(OleDbConnection connection = new OleDbConnection(connectionString)) { using(OleDbCommand command = new OleDbCommand(sql, connection)) { using(OleDbDataAdapter adapter = new OleDbDataAdapter(command)) { DataTable dataTable = new DataTable(); dataTable.Locale = CultureInfo.CurrentCulture; adapter.Fill(dataTable); return dataTable; } } } } #endregion #region 프로그램 시작하기 - Main() /// <summary> /// 프로그램 시작하기 /// </summary> private static void Main() { string applicationDirectoryPath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location); string sourceFilePath = Path.Combine(applicationDirectoryPath, "sample.csv"); DataTable dataTable = GetDataTable(sourceFilePath, true); foreach(DataRow dataRow in dataTable.Rows) { Console.WriteLine($"{dataRow[0]} {dataRow[1]}"); } } #endregion } } |
※ OLE DB는 32비트 버전만 사용 가능하다.