[C# FTP] C# FTP 접속 및 파일 업로드 하기


안녕하세요.

 

오늘은 C# FTP 두 번째 시간으로, C#에서 FTP 접속 후, 파일을 업로드 하는 방법에 대하여 알려드리려고 합니다.

 

당연히 테스트할 FTP 서버가 구축되어 있다고 가정하에 블로그 글을 포스팅 합니다!


 

참고해 주세요~~

 

그럼 바로 지난번 FTP 접속 소스코드에 이어서 Upload 소스코드 까지 작성해 보도록 하겠습니다.

 

예제 코드


[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

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 UpLoad(string folder, string filename)

        {

            return upload(folder, filename);

        }

 

        /// <summary>

        /// 파일 업로드

        /// </summary>

        /// <param name="folder"></param>

        /// <param name="filename"></param>

        /// <returns></returns>

        private bool upload(string folder, string filename)

        {

            try

            {

                makeDir(folder);

 

                FileInfo fileInf = new FileInfo(filename);

 

                folder = folder.Replace('\\''/');

                filename = filename.Replace('\\''/');

 

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

                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.UploadFile;

                ftpRequest.ContentLength = fileInf.Length;

 

                int buffLength = 2048;

                byte[] buff = new byte[buffLength];

                int contentLen;

 

                using (FileStream fs = fileInf.OpenRead())

                {

                    using (Stream strm = ftpRequest.GetRequestStream())

                    {

                        contentLen = fs.Read(buff, 0, buffLength);

 

                        while (contentLen != 0)

                        {

                            strm.Write(buff, 0, contentLen);

                            contentLen = fs.Read(buff, 0, buffLength);

                        }

                    }

 

                    fs.Flush();

                    fs.Close();

                }

 

                if (buff != null)

                {

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

                    buff = null;

                }

            }

            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;

        }

 

 

        private void makeDir(string dirName)

        {

            string[] arrDir = dirName.Split('\\');

            string currentDir = string.Empty;

 

            try

            {

                foreach (string tmpFoler in arrDir)

                {

                    try

                    {

                        if (tmpFoler == string.Empty) continue;

 

                        currentDir += @"/" + tmpFoler;

 

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

                        FtpWebRequest ftpRequest =

 (FtpWebRequest)WebRequest.Create(url);

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

 

                        ftpRequest.Method = WebRequestMethods.Ftp.MakeDirectory;

                        ftpRequest.KeepAlive = false;

                        ftpRequest.UsePassive = false;

 

                        FtpWebResponse response = 

(FtpWebResponse)ftpRequest.GetResponse();

                        response.Close();

                    }

                    catch { }

                }

            }

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

            }

        }

 

        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

60

61

62

63

64

65

66

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();

 

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

 

 

            string path = string.Empty;

            string fileName = string.Empty;

            string localPath = @"C:\Users\Desktop\"; //바탕화면 경로를 Local Path 기준으로 

            path = @"DATA"; //업로드  파일 저장할 FTP 경로 지정

            DirectoryInfo dirInfo = new DirectoryInfo(localPath);

            FileInfo[] infos = dirInfo.GetFiles();

            if (result == true)

            {

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

                foreach (FileInfo info in dirInfo.GetFiles())

                {

                    if (Path.GetExtension(info.Name) == ".txt") //txt 확장자 파일만 FTP 서버에 Upload

                    {

                        if (manager.UpLoad(path, info.FullName) == false) //파일 업로드

                        {

                            Console.WriteLine("FTP Upload 실패");

                        }

                        else

                        {

                            Console.WriteLine("FTP Upload 시작");

                            Console.WriteLine("FTP Upload 완료");

                        }

                    }

                }

            }

            else

            {

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

            }

        }

    }

}

Colored by Color Scripter

cs


실행 결과




위와 같이 FTP 서버에 업로드 할 .txt 확장자 파일이 2개가 있습니다.

 

프로그램을 실행시킨 결과

 



위와 같이 FTP 경로에 txt 파일 2개가 알맞게 업로드 된 것을 확인하실 수 있습니다.

 

이로써, 오늘은 FTP 접속 및 업로드 하는 방법에 대해서 알아 보았습니다.

 

감사합니다.^^


728x90

이 글을 공유하기

댓글

Designed by JB FACTORY