[C# FTP] C# FTP 접속 및 파일 다운로드


안녕하세요.

 

오늘은 C#  FTP 3 시간으로 오늘은 지난번에 접속, 파일 업로드 다음으로 파일 다운로드 하는 방법에 대해서 알려 드리려고 합니다.

 

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

75

76

77

78

79

80

81

82

83

84

85

86

87

88

89

90

91

92

93

94

95

96

97

98

99

100

101

102

103

104

105

106

107

108

109

110

111

112

113

114

115

116

117

118

119

120

121

122

123

124

125

126

127

128

129

130

131

132

133

134

135

136

137

138

139

140

141

142

143

144

145

146

147

148

149

150

151

152

153

154

155

156

157

158

159

160

161

162

163

164

165

166

167

168

169

170

171

172

173

174

175

176

177

178

179

180

181

182

183

184

185

186

187

188

189

190

191

192

193

194

195

196

197

198

199

200

201

202

203

204

205

206

207

208

209

210

211

212

213

214

215

216

217

218

219

220

221

222

223

224

using System;

using System.Collections.Generic;

using System.IO;

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;

        }

 

        public bool DownLoad(string localFullPathFile, string serverFullPathFile)

        {

            return download(localFullPathFile, serverFullPathFile);

        }

 

        public List<string> GetFileList(string serverFolder)

        {

            return getFileList(serverFolder);

        }

 

        private bool download(string localFullPathFile, string serverFullPathFile)

        {

            try

            {

                checkDir(localFullPathFile);

 

                string url = 

                    string.Format

                    (@"FTP://{0}:{1}/{2}"this.ipAddr, this.port, serverFullPathFile);

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

 

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

                ftpRequest.KeepAlive = false;

                ftpRequest.UseBinary = true;

                ftpRequest.UsePassive = false;

 

                using (FtpWebResponse response = (FtpWebResponse)ftpRequest.GetResponse())

                {

                    using (FileStream outputStream = 

                        new FileStream(localFullPathFile, FileMode.Create, FileAccess.Write))

                    {

                        using (Stream ftpStream = response.GetResponseStream())

 

                        {

                            int bufferSize = 2048;

                            int readCount;

                            byte[] buffer = new byte[bufferSize];

 

                            readCount = ftpStream.Read(buffer, 0, bufferSize);

                            while (readCount > 0)

                            {

                                outputStream.Write(buffer, 0, readCount);

                                readCount = ftpStream.Read(buffer, 0, bufferSize);

                            }

 

                            ftpStream.Close();

                            outputStream.Close();

 

                            if (buffer != null)

                            {

                                Array.Clear(buffer, 0, buffer.Length);

                                buffer = null;

                            }

                        }

 

                    }

                }

 

                return true;

            }

            catch (Exception ex)

            {

                this.LastException = ex;

 

                if (serverFullPathFile.Contains(@"\ZOOM\") == true)

                    return false;

                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;

            }

        }

        private List<string> getFileList(string serverFolder)

        {

            List<string> resultList = new List<string>();

            StringBuilder result = new StringBuilder();

            try

            {

                string url = string.Format

                    (@"FTP://{0}:{1}/{2}", this.ipAddr, this.port, serverFolder);

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

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

                ftpRequest.KeepAlive = false;

                ftpRequest.UseBinary = false;

                ftpRequest.UsePassive = false;

 

                ftpRequest.Method = WebRequestMethods.Ftp.ListDirectory;

 

                using (WebResponse response = ftpRequest.GetResponse())

                {

                    StreamReader reader = new StreamReader(response.GetResponseStream());

 

                    string line = reader.ReadLine();

                    while (line != null)

                    {

                        result.Append(line);

                        result.Append("\n");

                        line = reader.ReadLine();

                    }

                    result.Remove(result.ToString().LastIndexOf('\n'), 1);

 

                    if (reader != null) reader.Close();

 

                    foreach (string file in result.ToString().Split('\n'))

                    {

                        resultList.Add(file);

                    }

                }

 

                return resultList;

            }

            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 resultList;

            }

        }

 

        private void checkDir(string localFullPathFile)

        {

            FileInfo fInfo = new FileInfo(localFullPathFile);

 

            if (!fInfo.Exists)

            {

                DirectoryInfo dInfo = 

                    new DirectoryInfo(fInfo.DirectoryName);

                if (!dInfo.Exists)

                {

                    dInfo.Create();

                }

            }

        }

    }

}

 

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

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

using System;

using System.Collections.Generic;

using System.IO;

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"//IP 주소

            user = "user01"//FTP 접속 계정

            pwd = "@123qwe"//FTP 계정 비밀번호

            port = "21";     //FTP 접속 Port

 

            FTPManager manager = new FTPManager();

 

            //FTP 접속

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

 

 

            string serverPath = string.Empty;

            string localPath = string.Empty;

 

            serverPath = @"DATA\DATA123.txt"//다운로드 받을 FTP 상세 경로 

 

            //FTP에서 다운 받은 파일을 저장할 Local 경로 설정

            localPath = @"C:\Users\winforsys\Desktop\FTP_Download\test.txt"

 

            if (result == true)

            {

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

 

                if (manager.DownLoad(localPath, serverPath) == true)

                {

                    Console.WriteLine("Download Success!");

                }

                else

                {

                    Console.WriteLine("Download Fail!");

                }

            }

            else

            {

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

            }

        }

    }

}

 

Colored by Color Scripter

cs

 

실행 결과



프로그램을 실행 시켜 보시면




 

위와 같이 FTP 서버에 있는 “DATA123.txt” 파일이 제가 원하는 경로인 FTP_Download 폴더 안에 “test.txt” 파일이 알맞게 다운로드 되어 생성된 것을 확인하실 수 있습니다.

 

이로써, 오늘은 FTP에서 파일 다운로드 하는 방법에 대해서 알아 보았습니다.

 

감사합니다.^^

728x90

이 글을 공유하기

댓글

Designed by JB FACTORY