[C# 윈폼] C# 에서 .csv 파일 읽기(Read)


안녕하세요.

 

오늘은 C#에서 .csv 파일을 읽어오는 방법에 대해서 알려 드리려고 합니다.

 

csv 파일은 구분자가 ‘,’ 로 이루어진 파일을 이루어서 말하는데요. 실무를 하다보면 csv 파일을 쉽게 접하시면서 또 읽어서 사용하는 경우가 종종 있습니다.

 

이럴 경우를 대비해서 연습해 두시면 좋을 것 같아요!

 

그럼 바로 어떻게 csv 파일을 읽어 오는지 보여 드리도록 하겠습니다.

 

먼저 아래와 같이 윈폼 프로젝트를 생성해 주시고, Button 컨트롤 , TextBox 컨트롤을 배치해 주시기 바랍니다.


윈폼 프로젝트 생성 및 컨트롤 배치




그럼 이제 CSV Read 버튼을 클릭하면 먼저 CSV 파일이 있는 폴더의 경로를 읽어와서 그 안에 csv 파일들만 List 형태로 가져와서 CSV 파일을 읽어온 데이터를 Text 컨트롤에 배치해 보도록 소스코드를 작성해 보도록 하겠습니다.


예제 코드


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

using System;

using System.Collections.Generic;

using System.ComponentModel;

using System.Data;

using System.Drawing;

using System.IO;

using System.Linq;

using System.Text;

using System.Threading.Tasks;

using System.Windows.Forms;

 

namespace Test

{

    public partial class Form1 : Form

    {

        List<string> csvList = null;

 

        public Form1()

        {

            InitializeComponent();

 

            //버튼 이벤트 선언

            uiBtn_Read.Click += uiBtn_Read_Click;

        }

 

        /// <summary>

        /// CSV 읽기 버튼 클릭 이벤트 핸들러

        /// </summary>

        /// <param name="sender"></param>

        /// <param name="e"></param>

        public void uiBtn_Read_Click(object sender, EventArgs e)

        {

            FolderBrowserDialog fbd = new FolderBrowserDialog();

 

            if(fbd.ShowDialog() == DialogResult.OK)

            {

                string[] fileName = Directory.GetFiles(fbd.SelectedPath); //폴더 읽어와

                csvList = fileName.Where(x => x.IndexOf(".csv"

StringComparison.OrdinalIgnoreCase) >= 0)

                               .Select(x => x).ToList();

 

                string result = string.Empty;

 

                try

                {

                    GetCSVData(csvList, result); //CSV 파일 내용 읽어오기

                }

                catch { }

            }

        }

 

        public void GetCSVData(List<string> csvList, string result)

        {

            for (int idx = 0; idx < csvList.Count; idx++)

            {

                using (var sr = new System.IO.StreamReader(csvList[idx]))

                {

                    while (!sr.EndOfStream)

                    {

                        string array = sr.ReadLine();

                        string[] values = array.Split(',');

 

                        for (int i = 0; i < values.Length; i++)

                        {

                            result += " " + values[i];

                        }

                    }

                }

 

                textBox1.Text = result;

            }

        }

    }

}

 

Colored by Color Scripter

cs


실행 결과




위와 같이 제가 test.csv 파일을 바탕화면 경로에 만들어 놓았었고 그 폴더를 읽어오니까 csv 데이터가 알맞게 읽어와 져서 TextBox에 출력된 모습을 확인하실 수 있습니다.

 

감사합니다.


728x90

이 글을 공유하기

댓글

Designed by JB FACTORY