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

안녕하세요.

 

오늘은 C# 윈폼에서 FTP 파일서버에 접속 하여 특정 경로에 파일을 업로드 하는 방법에 대해서 알려 드리려고 합니다.

 

실무에서 프로젝트를 하시다 보면, FTP 연결을 종종 하는 경우가 있는데요. 이럴때 유용하게 사용하실 수 있을거라 생각합니다.

 

특별한 설명 없이 바로 예제 코드들을 통해서 FTP 접속 및 Upload 하는 방법을 보여 드리도록 하겠습니다.

 

 

FileManager.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
using System;
using System.IO;
using System.Text;
 
namespace FtpUploadTest.Class
{
    /// <summary>
    /// Text File Parsing Class
    /// </summary>
    public class FileManager
    {
        /// <summary>
        /// FileName : Parsing 할 파일명
        /// Exception : 마지막으로 발생한 Error 메세지
        /// </summary>
        public static string FileName { get; set; }
        public static string Exception { get { return _exception; } }
 
        private static string _exception;
 
        /// <summary>
        /// 파일을 Parsing 하여 찾는 Value를 반환해줌
        /// </summary>
        /// <param name="SectionName">최상위 Section [ ]로 묶여 있음</param>
        /// <param name="KeyName">찾고자 하는 Key 값. = 앞에 있음</param>
        /// <param name="DefaultValue">찾는 값이 없을 경우 반환할 기본 값</param>
        /// <returns></returns>
        public static string GetValueString(string SectionName, string KeyName, string DefaultValue)
        {
            _exception = string.Empty;
 
            if (FileName == null || FileName.Length == 0return DefaultValue;
 
            string value = string.Empty;
            bool IsSection = false;
 
            try
            {
                StreamReader sr = new StreamReader(FileName);
 
                string lineString = string.Empty;
 
                while (lineString != null)
                {
                    lineString = sr.ReadLine();
 
                    if (lineString == nullbreak;
 
                    if (lineString.StartsWith(";")) continue;
 
                    if (lineString.Contains("["&& lineString.Contains("]"))
                    {
                        IsSection = lineString.Contains(string.Format("[{0}]", SectionName));
                    }
 
                    if (IsSection && lineString.Contains(KeyName))
                    {
                        value = lineString.Replace(KeyName, "").Replace("=""").Trim();
                        break;
                    }
                }
 
                sr.Close();
            }
            catch (Exception ex)
            {
                _exception = ex.Message;
 
                return DefaultValue;
            }
 
            if (value == string.Empty) return DefaultValue;
 
            return value;
        }
 
        /// <summary>
        /// int 값을 반환해주는 함수
        /// </summary>
        /// <param name="SectionName">최상위 Section [ ]로 묶여 있음</param>
        /// <param name="KeyName">찾고자 하는 Key 값. = 앞에 있음</param>
        /// <param name="DefaultValue">찾는 값이 없을 경우 반환할 기본 값</param>
        /// <returns></returns>
        public static int GetValueInt(string SectionName, string KeyName, int DefaultValue)
        {
            _exception = string.Empty;
 
            if (FileName.Length == 0return DefaultValue;
 
            bool IsSection = false;
            string value = string.Empty;
 
            try
            {
                StreamReader sr = new StreamReader(FileName);
 
                string lineString = string.Empty;
 
                while (lineString != null)
                {
                    lineString = sr.ReadLine();
 
                    if (lineString == nullbreak;
 
                    if (lineString.StartsWith(";")) continue;
 
                    if (lineString.Contains("["&& lineString.Contains("]"))
                    {
                        IsSection = lineString.Contains(string.Format("[{0}]", SectionName));
                    }
 
                    if (IsSection && lineString.Contains(KeyName))
                    {
                        value = lineString.Replace(KeyName, "").Replace("=""").Replace(" """);
                        break;
                    }
                }
 
                sr.Close();
 
                if (value == string.Empty) return DefaultValue;
 
                return int.Parse(value);
            }
            catch (Exception ex)
            {
                _exception = ex.Message;
 
                return DefaultValue;
            }
        }
 
        /// <summary>
        /// 선택 된 File 에 Value를 변경함
        /// </summary>
        /// <param name="SectionName">변경 하고자 하는 Section</param>
        /// <param name="KeyName">변경 하고자 하는 Key</param>
        /// <param name="ValueString">변경 값</param>
        /// <returns></returns>
        public static bool SetValue(string SectionName, string KeyName, string ValueString)
        {
            _exception = string.Empty;
 
            if (FileName.Length == 0return false;
 
            bool IsSection = false;
            string value = string.Empty;
 
            try
            {
                StreamReader sr = new StreamReader(FileName);
 
                StringBuilder strContent = new StringBuilder();
 
                string lineString = string.Empty;
 
                while (lineString != null)
                {
                    lineString = sr.ReadLine();
 
                    if (lineString == nullbreak;
 
                    if (lineString.StartsWith(";")) continue;
 
                    if (lineString.Contains("["&& lineString.Contains("]"))
                    {
                        IsSection = lineString.Contains(string.Format("[{0}]", SectionName));
                    }
 
                    if (IsSection && lineString.Contains(KeyName))
                    {
                        value = lineString.Replace(KeyName, "").Replace("=""").Replace(" """);
 
                        strContent.AppendLine(lineString.Replace(value, ValueString));                        
                    }
                    else
                    {
                        strContent.AppendLine(lineString);
                    }                
                }
 
                sr.Close();
 
                StreamWriter sw = new StreamWriter(FileName);
 
                sw.Flush();
                sw.Write(strContent.ToString());
                sw.Close();
            }
            catch (Exception ex)
            {
                _exception = ex.Message;
                return false;
            }
 
            return true;
        }
    }
}
 
cs

 

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
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.IO;
 
namespace FtpUploadTest.Class
{
    public class FTPManager
    {
        public delegate void OccureExceptionEventHandler(string LocationID, Exception ex);
        event OccureExceptionEventHandler ExceptionEvent;
 
        #region " Properties & Variables "
 
        private static FTPManager instance;
 
        public static FTPManager Instance
        {
            get
            {
                if (instance == null) instance = new FTPManager();
 
                return instance;
            }
        }
 
        public Exception LastException = null;
 
        public bool IsConnected { get; set; }
 
        public string ipAddr = string.Empty;
        public string port = string.Empty;
        public string userId = string.Empty;
        public string pwd = string.Empty;
        
        #endregion " Properties & Variables End"
 
        #region " Create & Load "
 
        public FTPManager()
        {
 
        }
 
        #endregion " Create & Load End"
 
        #region "  Public methode "
 
        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 = true;
 
                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 bool UpLoad(string folder, string filename)
        {
            return upload(folder, filename);
        }
 
        public bool Delete(string folder, string filename)
        {
            return deleteFile(folder, filename);
        }
 
        public List<string> GetFileList(string serverFolder)
        {
            return getFileList(serverFolder);
        }
 
        #endregion "  Public methode End"
 
        #region "  Private methode "
 
        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 = true;
 
                using (FtpWebResponse response = (FtpWebResponse)ftpRequest.GetResponse())
                {
                    FileStream outputStream = new FileStream(localFullPathFile, FileMode.Create,FileAccess.Write);
                    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();
                }
 
                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 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 = true;
                ftpRequest.UsePassive = true;
 
                ftpRequest.Method = WebRequestMethods.Ftp.UploadFile;
                ftpRequest.ContentLength = fileInf.Length;
 
                int buffLength = 2048;
                byte[] buff = new byte[buffLength];
                int contentLen;
 
                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();
            }
            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 bool deleteFile(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 = true;
                ftpRequest.UsePassive = true;
 
                ftpRequest.Method = WebRequestMethods.Ftp.DeleteFile;
 
                FtpWebResponse response = (FtpWebResponse)ftpRequest.GetResponse();
                response.Close();
            }
            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 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 = true;
                ftpRequest.UsePassive = true;
 
                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);
                    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 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 = true;
 
                        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();
                }
            }
        }
 
        #endregion "  Private methode End"
 
        #region " Form Events "
 
        #endregion " Form Events End"
    }
}
 
cs

 

Config.ini
1
2
3
4
5
6
7
8
9
10
11
12
13
14
 
 
[FTP]
ADDR=127.0.0.1
USER=test01
PWD=test01
PORT=21
 
[TEST]
FTP_PATH=TEST
TEST_CREAATE_XML_PATH=D:\TEST
TEST_SUCCESS_PATH=D:\TEST\TEST_FILE_UPLOAD_SUCCESS
TEST_FAILURE_PATH=D:\TEST\TEST_FILE_UPLOAD_FAIL
FILE_DELETE_DAY=14
cs

 

Program.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
using FtpUploadTest.Class;
 
namespace XML_Parser
{
    class Program
    {
        public FTPManager Manager = new FTPManager();
 
        static void Main(string[] args)
        {
            Program pro = new Program();
 
            pro.GetFtpPath(pro);
            pro.FtpFileUploadDelete(pro);
        }
 
        /// <summary>
        /// 4초마다 파일 업로드 및 삭제 반복
        /// </summary>
        /// <param name="pro"></param>
        private void FtpFileUploadDelete(Program pro)
        {
            while (true)
            {
                Upload_Xml_File(pro, "test");
 
                System.Threading.Thread.Sleep(4000);
 
            }
        }
 
        /// <summary>
        /// FTP에 파일 업로드
        /// </summary>
        /// <param name="pro"></param>
        /// <param name="fileName"></param>
        /// <returns></returns>
        private static bool Upload_Xml_File(Program pro , string fileName)
        {
            bool result = false;
 
            string dataPath = "\\TEST\\";
            string localPath = @"D:\BEOMBEOMJOJO\test.xml";
 
            //XMl File Uolad
            if (pro.Manager.UpLoad(dataPath, localPath) == false)
            {
                //Program.ShowLog(LogType.Error, string.Format("XML File Upload Fail.\n[Local PATH : {0}]\n[Server PATH : {1}{2}]", localPath, dataPath, fileName));
            }
            else
            {
                //Program.ShowLog(LogType.Inform, string.Format("XML File Upload Complete.\n[Local PATH : {0}]\n[Server PATH : {1}{2}]", localPath, dataPath, fileName));
                result = true;
            }
 
            System.Threading.Thread.Sleep(4000);
 
            //XMl File Delete
            if (pro.Manager.Delete(dataPath, localPath) == false)
            {
                //Program.ShowLog(LogType.Error, string.Format("XML File Delete Fail.\n[Local PATH : {0}]\n[Server PATH : {1}{2}]", localPath, dataPath, fileName));
            }
            else
            {
                //Program.ShowLog(LogType.Inform, string.Format("XML File Delete Complete.\n[Local PATH : {0}]\n[Server PATH : {1}{2}]", localPath, dataPath, fileName));
                result = true;
            }
 
            return result;
        }
 
        /// <summary>
        /// FTP 접속 정보 설정 메서드
        /// </summary>
        /// <param name="pro"></param>
        private void GetFtpPath(Program pro)
        {
 
            string addr = string.Empty;
            string port = string.Empty;
            string userId = string.Empty;
            string pw = string.Empty;
 
            addr = FileManager.GetValueString("FTP""ADDR""127.0.0.1");
            port = FileManager.GetValueString("FTP""PORT""21");
            userId = FileManager.GetValueString("FTP""USER""test01");
            pw = FileManager.GetValueString("FTP""PWD""test01");
 
            pro.Manager.ipAddr = addr;
            pro.Manager.port = port;
            pro.Manager.userId = userId;
            pro.Manager.pwd = pw;
        }
    }
}
 
 
cs

 

위의 예제 코드는 제가 FTP에 접속을 해서 특정 경로에 파일 업로드 및 파일 삭제를 주기적으로 하는 예제 프로그램을 만든 것입니다.

 

여기서 핵심은 FTPManager.cs 클래스 이고, 이 소스코드 안에 FTP 접속, 파일 업로드, 다운로드, 삭제 로직들이 들어가 있으므로 이 부분을 응용하여 이용하시면 되겠습니다.

 

감사합니다.^^

728x90

이 글을 공유하기

댓글

Designed by JB FACTORY