메뉴 건너뛰기

라이온하트 2nd edition

홈페이지를 새롭게 리뉴얼합니다.

C#
2013.11.04 06:30

C# FTP 종합

조회 수 211240 추천 수 0 댓글 0
?

단축키

Prev이전 문서

Next다음 문서

크게 작게 위로 아래로 댓글로 가기 인쇄
?

단축키

Prev이전 문서

Next다음 문서

크게 작게 위로 아래로 댓글로 가기 인쇄

FTP로 파일을 전송할 일이 있다면 아래 처럼 간단히 구성하여 사용한다.
ftpUtil.cs (클래스 파일)

 

using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Net;
using System.Windows.Forms;


namespace FTP
{
    public delegate void FTPDownloadTotalSizeHandle(long totalSize);
    public delegate void FTPDownloadReceivedSizeHandle(int RcvSize);

    class ftpUtil
    {   
        public event FTPDownloadTotalSizeHandle ftpDNTotalSizeEvt;
        public event FTPDownloadReceivedSizeHandle ftpDNRcvSizeEvt;

        string ftpServerIP = null;
        string ftpUserID = null;
        string ftpPassword = null;
        string ftpPort = null;
        bool usePassive = false;

       
  //ftpUtil 객체를 생성할때 생성자에 인자로 필요한 값들을 넣어준다.
      public ftpUtil(string ip, string id, string pw, string port)
        {
            ftpServerIP = ip;   //FTP 서버주소
            ftpUserID = id;     //아이디
            ftpPassword = pw;  //패스워드
            ftpPort = port;        //포트
            usePassive = true;   //패시브모드 사용여부
        } 

        /// <summary>
        /// Method to upload the specified file to the specified FTP Server
        /// </summary>
        /// <param name="filename">file full name to be uploaded</param>
        //파일 업로드
        public Boolean Upload(string folder,string filename)
        {
            FileInfo fileInf = new FileInfo(filename);
            string uri = "ftp://" + ftpServerIP + ":"+ftpPort+"/"+folder+"/" + fileInf.Name;
            FtpWebRequest reqFTP;

            // Create FtpWebRequest object from the Uri provided
            reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(uri));

            // Provide the WebPermission Credintials
            reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
           
            // By default KeepAlive is true, where the control connection is not closed
            // after a command is executed.
            reqFTP.KeepAlive = false;

            // Specify the command to be executed.
            reqFTP.Method = WebRequestMethods.Ftp.UploadFile;

            // Specify the data transfer type.
            reqFTP.UseBinary = true;
            reqFTP.UsePassive = usePassive;

            // Notify the server about the size of the uploaded file
            reqFTP.ContentLength = fileInf.Length;

            // The buffer size is set to 2kb
            int buffLength = 2048;
            byte[] buff = new byte[buffLength];
            int contentLen;

            // Opens a file stream (System.IO.FileStream) to read the file to be uploaded
            FileStream fs = fileInf.OpenRead();

            try
            {
                // Stream to which the file to be upload is written
                Stream strm = reqFTP.GetRequestStream();

                // Read from the file stream 2kb at a time
                contentLen = fs.Read(buff, 0, buffLength);

                // Till Stream content ends
                while (contentLen != 0)
                {
                    // Write Content from the file stream to the FTP Upload Stream
                    strm.Write(buff, 0, contentLen);
                    contentLen = fs.Read(buff, 0, buffLength);
                }

                // Close the file stream and the Request Stream
                strm.Close();
                fs.Close();

                return true;
            }

            catch{

                MessageBox.Show("FTP 전송중 문제가 발생하였습니다.네트워크 상황 또는 접속정보를 살펴 보시기 바랍니다.");
                return false;
            }
            //catch (Exception ex){MessageBox.Show(ex.Message, "Upload Error");}
            
        }

     //파일 삭제         
    public void DeleteFTP(string fileName)
        {
            try
            {
                string uri = "ftp://" + ftpServerIP + "/" + fileName;
                FtpWebRequest reqFTP;
                reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri("ftp://" + ftpServerIP + "/" + fileName));

                reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
                reqFTP.KeepAlive = false;
                reqFTP.Method = WebRequestMethods.Ftp.DeleteFile;

                string result = String.Empty;
                FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
                long size = response.ContentLength;
                Stream datastream = response.GetResponseStream();
                StreamReader sr = new StreamReader(datastream);
                result = sr.ReadToEnd();
                sr.Close();
                datastream.Close();
                response.Close();
            }
            catch{return;}
            //catch (Exception ex){MessageBox.Show(ex.Message, "FTP 2.0 Delete");}
        }

        
       public bool GetFilesInfo(string filename, ref DateTime dt)
        {
            try
            {
                FtpWebRequest reqFTP;
                reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri("ftp://" + ftpServerIP + "/" + filename));
                reqFTP.UseBinary = true;
                reqFTP.UsePassive = usePassive;
                reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
                reqFTP.Method = WebRequestMethods.Ftp.GetDateTimestamp;

                FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
                dt = response.LastModified;

                response.Close();
                return true;

            }
            catch { return false; }
            //catch (Exception ex){System.Windows.Forms.MessageBox.Show(ex.Message);return false;}
        }

        public List<string> GetFilesDetailList(string subFolder)
        {
            List<string> files = new List<string>();
            string line = null;


            try
            {
                //StringBuilder result = new StringBuilder();

                FtpWebRequest ftp;
                ftp = (FtpWebRequest)FtpWebRequest.Create(new Uri("ftp://" + ftpServerIP + "/" + subFolder));
                ftp.UseBinary = true;                
                ftp.UsePassive = usePassive;
                ftp.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
                ftp.Method = WebRequestMethods.Ftp.ListDirectoryDetails;

                WebResponse response = ftp.GetResponse();
                StreamReader reader = new StreamReader(response.GetResponseStream(), System.Text.Encoding.Default);                        

 

                while ((line = reader.ReadLine()) != null)
                {  
                    files.Add(line);                 
                }

                reader.Close();
                response.Close();
                return files;
                //MessageBox.Show(result.ToString().Split('n'));
            }
            catch{return files;}
            //catch (Exception ex){System.Windows.Forms.MessageBox.Show(ex.Message);return files;}
        }

        public string[] GetFileList(string subFolder)
        {
            string[] downloadFiles;
            StringBuilder result = new StringBuilder();
            FtpWebRequest reqFTP;
            try
            {
                reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri("ftp://" + ftpServerIP + "/" + subFolder));
                reqFTP.UseBinary = true;
                reqFTP.UsePassive = usePassive;
                reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
                reqFTP.Method = WebRequestMethods.Ftp.ListDirectory;
                WebResponse response = reqFTP.GetResponse();
                StreamReader reader = new StreamReader(response.GetResponseStream());
                //MessageBox.Show(reader.ReadToEnd());
                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();
                response.Close();
                //MessageBox.Show(response.StatusDescription);
                return result.ToString().Split('n');
            }
            catch
            {                
                downloadFiles = null;
                return downloadFiles;
            }
            /*
            catch (Exception ex)
            {
                System.Windows.Forms.MessageBox.Show(ex.Message);
                downloadFiles = null;
                return downloadFiles;
            }
            */
        }

        public bool checkDir(string localFullPathFile)
        {
            FileInfo fInfo = new FileInfo(localFullPathFile);

            if(!fInfo.Exists){
                DirectoryInfo dInfo = new DirectoryInfo(fInfo.DirectoryName);
                if(!dInfo.Exists){
                    dInfo.Create();
                }
                //dInfo.Delete();
            }

            //fInfo.Delete();
            return true;

        }
        public bool Download(string localFullPathFile, string serverFullPathFile)
        {
            FtpWebRequest reqFTP;
            try
            {
                //filePath = <<The full path where the file is to be created.>>, 
                //fileName = <<Name of the file to be created(Need not be the name of the file on FTP server).>>
                checkDir(localFullPathFile);
                FileStream outputStream = new FileStream(localFullPathFile, FileMode.Create);

                reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri("ftp://" + ftpServerIP + "/" + serverFullPathFile));
                reqFTP.Method = WebRequestMethods.Ftp.DownloadFile;
                reqFTP.UseBinary = true;
                reqFTP.UsePassive = usePassive;
                reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
                FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
                Stream ftpStream = response.GetResponseStream();
                long cl = response.ContentLength;

                if (ftpDNTotalSizeEvt != null) ftpDNTotalSizeEvt(cl);

                int bufferSize = 2048;
                int readCount;
                byte[] buffer = new byte[bufferSize];

                readCount = ftpStream.Read(buffer, 0, bufferSize);
                while (readCount > 0)
                {
                    if (ftpDNRcvSizeEvt != null) ftpDNRcvSizeEvt(readCount);

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

                ftpStream.Close();
                outputStream.Close();
                response.Close();
                return true;
            }
            catch { return false; }
            /*
            catch (Exception ex)
            {
                MessageBox.Show("download()"+ex.Message);
                return false;
            }
            */
        }

        private long GetFileSize(string filename)
        {
            FtpWebRequest reqFTP;
            long fileSize = 0;
            try
            {
                reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri("ftp://" + ftpServerIP + "/" + filename));
                reqFTP.Method = WebRequestMethods.Ftp.GetFileSize;
                reqFTP.UseBinary = true;
                reqFTP.UsePassive = usePassive;
                reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
                FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
                Stream ftpStream = response.GetResponseStream();

                fileSize = response.ContentLength;

                ftpStream.Close();
                response.Close();

                return fileSize;
            }

            catch { return fileSize; }
            /*
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            return fileSize;
            */
        }

        public void Rename(string currentFilename, string newFilename)
        {
            FtpWebRequest reqFTP;
            try
            {
                reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri("ftp://" + ftpServerIP + "/" + currentFilename));
                reqFTP.Method = WebRequestMethods.Ftp.Rename;
                reqFTP.RenameTo = newFilename;
                reqFTP.UseBinary = true;
                reqFTP.UsePassive = usePassive;
                reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
                FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
                Stream ftpStream = response.GetResponseStream();

                ftpStream.Close();
                response.Close();
            }

            catch { }
            /*
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            */
        }

        public void MakeDir(string dirName)
        {
            FtpWebRequest reqFTP;
            try
            {
                // dirName = name of the directory to create.
                reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri("ftp://" + ftpServerIP + "/" + dirName));
                reqFTP.Method = WebRequestMethods.Ftp.MakeDirectory;
                reqFTP.UseBinary = true;
                reqFTP.UsePassive = usePassive;
                reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
                FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
                Stream ftpStream = response.GetResponseStream();

                ftpStream.Close();
                response.Close();
            }
            catch{}
            /*
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            */
        }


    }
}

출처: http://cafe.naver.com/issu3/247


List of Articles
번호 분류 제목 글쓴이 날짜 조회 수
225 C# 이미지 영역 설정방법 LionHeart 2021.02.16 276247
224 OS PHP WebSocket (웹소켓) 라이브러리 Ratchet, ReactPHP, sandstone LionHeart 2021.01.28 272857
223 C# 표준편차 (볼린저밴드 구현을 위한) LionHeart 2015.04.29 260536
222 OS [스크랩] Nginx(1.9.5) 설치 및 성능테스트 LionHeart 2016.01.23 249573
221 C# FTP upload 기능 구현 LionHeart 2013.11.04 248421
220 C# libevent 및 libev로 네트워크 성능 향상 LionHeart 2013.10.23 226523
219 C# C# XML 쓰고 읽기 LionHeart 2015.02.10 225866
218 OS 리눅스 - 아파치 2.x 트래픽 제한 LionHeart 2014.08.26 225194
217 OS USB 저장장치에 의한 데이터 유출 방지 방법 1 LionHeart 2014.07.22 213686
216 C# How to encrypt and decrypt files using the AES encryption algorithm in C# LionHeart 2020.06.11 212917
» C# C# FTP 종합 LionHeart 2013.11.04 211240
214 Information 텔레그램 봇(botfather) LionHeart 2018.03.16 205623
213 Android [유니티3D엔진] 안드로이드 유니티 연동_JNI badung007 2013.10.26 191260
212 OS INSTALLING NVIDIA LINUX DRIVERS IN A XEN ENABLED KERNEL LionHeart 2014.08.21 189919
211 Information network simulator 3 (ns-3) overview LionHeart 2013.10.24 185565
210 OS Apache, DDoS 방어모듈 1 LionHeart 2014.10.01 169883
209 C# C# Simple FTP Class LionHeart 2014.01.29 169735
208 OS Realtek 8723be-bt 무선랜 드라이버 (한성 u44x ) LionHeart 2014.07.18 161422
207 OS [스크랩] RHEL/CentOS 7 에서 방화벽(firewalld) 설정하기 LionHeart 2016.01.29 159312
206 C# 웹캠 영상출력 LionHeart 2014.03.31 157168
Board Pagination ‹ Prev 1 2 3 4 5 6 7 8 9 10 ... 12 Next ›
/ 12