[C# 문법] C# FTP 접속하기


안녕하세요.

 

오늘은 C# 으로 FTP 접속하는 방법에 대해서 소스코드를 통해 어떻게 FTP 서버에 접속을 하는지 알려 드리려고 합니다.

 

실무에서 프로젝트를 하다보면, 파일을 주고받는 경우가 많이 생기고 이로 인해 자연스럽게 FTP 서버를 구축하여 해당 서버에 접속을 하고 거기에 파일을 업로드, 다운로드, 삭제 등을 하는 경우가 많습니다.


 

그래서 오늘은 FTP 첫 번째 시간으로 C#으로 FTP에 접속하는 방법에 대해서 알려드리려고 합니다.

 

그럼 바로 예제 코드를 통해서 어떻게 접속을 하는지 보여 드리겠습니다.


예제코드


[FTPManager.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

using System;

using System.Collections.Generic;

using System.Linq;

using System.Net;

using System.Text;

using System.Threading.Tasks;

 

namespace FtpTest

{

    public class FTPManager

    {

 

        public delegate void ExceptionEventHandler(string LocationID, Exception ex);

        public event ExceptionEventHandler ExceptionEvent;

 

        public Exception LastException = null;

 

        public bool IsConnected { get; set; }

 

        private string ipAddr = string.Empty;

        private string port = string.Empty;

        private string userId = string.Empty;

        private string pwd = string.Empty;

 

        public FTPManager()

        {

 

        }

 

 

        public bool ConnectToServer(string ip, string port, string userId, string pwd)

        {

            this.IsConnected = false;

 

            this.ipAddr = ip;

            this.port = port;

            this.userId = userId;

            this.pwd = pwd;

 

            string url = string.Format(@"FTP://{0}:{1}/"this.ipAddr, this.port);

 

            try

            {

                FtpWebRequest ftpRequest = (FtpWebRequest)WebRequest.Create(url);

                ftpRequest.Credentials = new NetworkCredential(userId, pwd);

                ftpRequest.KeepAlive = false;

                ftpRequest.Method = WebRequestMethods.Ftp.ListDirectory;

                ftpRequest.UsePassive = false;

 

                using (ftpRequest.GetResponse())

                {

 

                }

 

                this.IsConnected = true;

            }

            catch (Exception ex)

            {

                this.LastException = ex;

 

                System.Reflection.MemberInfo info = System.Reflection.MethodInfo.GetCurrentMethod();

                string id = string.Format("{0}.{1}", info.ReflectedType.Name, info.Name);

 

                if (this.ExceptionEvent != null)

                    this.ExceptionEvent(id, ex);

 

                return false;

            }

 

            return true;

        }

    }

}

 

Colored by Color Scripter

cs

 

[Main.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

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Threading.Tasks;

 

namespace FtpTest

{

    class Program

    {

        static void Main(string[] args)

        {

            //FTP 접속에 필요한 정보

            string addr = string.Empty;

            string user = string.Empty;

            string pwd = string.Empty;

            string port = string.Empty;

 

            addr = "127.0.0.1";

            user = "Test01";

            pwd = "@123qwe";

            port = "21";

 

            FTPManager manager = new FTPManager();

 

            bool result = manager.ConnectToServer(addr, port, user, pwd);

 

            if(result == true)

            {

                Console.WriteLine("FTP 접속 성공");

            }

            else

            {

                Console.WriteLine("FTP 접속 실패");

            }

        }

    }

}

 

Colored by Color Scripter

cs


실행 결과



 

위와 같이 FTP에 제대로 접속된 것을 확인하실 수 있습니다.

 

오늘은 간단히 FTP 접속하는 방법에 대해서 알아보았습니다.

다음은 이 소스코드를 베이스로 FTP에 파일 업로드, 다운로드, 삭제 하는 방법에 대해서 포스팅 하겠습니다.

 

감사합니다.^^


728x90

이 글을 공유하기

댓글

Designed by JB FACTORY