첨부 실행 코드는 나눔고딕코딩 폰트를 사용합니다.

728x90
반응형
728x170

TestProject.zip
0.11MB

▶ Program.cs

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비트 버전만 사용 가능하다.

728x90
반응형
그리드형(광고전용)
Posted by icodebroker

댓글을 달아 주세요