[Today I Learned] C# FTP통신으로 파일 전송법

suwoncityboyyy·2023년 5월 20일
0

C#, .net

목록 보기
3/3
post-thumbnail

FTPWebRequest ClassFTPWebResponse Class를 이용하여 FTP서버에 접속해서 업로드,다운로드 및 다운로드가 가능하다.

main.cs

namespace FTPTest
{
    public partial class Main : Form
    {
        string _ftpID = "user";
        string _ftpPassword = "1234";
        string _ftpServer = "127.0.0.1";
 
        string _uploadFilePath = "testimage.png";
        string _downloadFilePath = "testimage_download.png";
 
        public Main()
        {
            InitializeComponent();
        }
 
        private void btnUpLoad_Click(object sender, EventArgs e)
        {
            FTPClient ftpClient = new FTPClient(_ftpServer,_ftpID,_ftpPassword);
            ftpClient.UpLoad(_uploadFilePath, _uploadFilePath);
            picUpLoad.Load(string.Format(@"{0}",_uploadFilePath));
            picUpLoad.SizeMode = PictureBoxSizeMode.StretchImage;
        }
        private void btnDownLoad_Click(object sender, EventArgs e)
        {
            FTPClient ftpClient = new FTPClient(_ftpServer, _ftpID, _ftpPassword);
            ftpClient.DownLoad(_uploadFilePath, _downloadFilePath);
            picDownLoad.Load(string.Format(@"{0}", _uploadFilePath));
            picDownLoad.SizeMode = PictureBoxSizeMode.StretchImage;
        }
    }
}

이미지를 전송하기위해서는 이진데이터로 전송해야되므로 BinaryReader클래스를 사용해서 업로드하는 파일값을 읽어서 FTP서버로 업로드 한다.

업로드(upload) sample

upload.cs

public void UpLoad(string filePath, string uploadPath)
{
    //FTP다운로드관련 URL, Method설정(UploadFile)
    string uri = string.Format("ftp://{0}/{1}", _serverIP, uploadPath);
    FtpWebRequest request = (FtpWebRequest)WebRequest.Create(uri);
    request.Method = WebRequestMethods.Ftp.UploadFile;                      
    request.Credentials = new NetworkCredential(_id, _password);
 
    //파일정보를 Byte로열기
    byte[] fileContents = null;
    using (BinaryReader br = new BinaryReader(File.Open(filePath, FileMode.Open)))
    {
        long dataLength = br.BaseStream.Length;
        fileContents = new byte[br.BaseStream.Length];
        fileContents = br.ReadBytes((int) br.BaseStream.Length);
    }
 
    //FTP서버에 파일전송처리
    request.ContentLength = fileContents.LongLength;
    using (Stream requestStream = request.GetRequestStream())
    {
        requestStream.Write(fileContents, 0, fileContents.Length);
    }
 
    //FTP전송결과확인
    using (FtpWebResponse response = (FtpWebResponse)request.GetResponse())
    {
        Console.WriteLine($"Upload File Complete, status {response.StatusDescription}");
    }        
}

download sample

download.cs

public void DownLoad(string downloadPath, string saveFilePath)
{
    string uri = string.Format("ftp://{0}/{1}", _serverIP, downloadPath);
    FtpWebRequest request = (FtpWebRequest)WebRequest.Create(uri);
    request.Method = WebRequestMethods.Ftp.DownloadFile;
    request.Credentials = new NetworkCredential(_id, _password);
 
    FtpWebResponse response = (FtpWebResponse)request.GetResponse();
    Stream responseStream = response.GetResponseStream();
 
    int fileContentsLength = 4096;
    byte[] fileContents = new byte[fileContentsLength];
 
    Stream stream = new FileStream(saveFilePath, FileMode.Create);
 
    using (BinaryWriter bw = new BinaryWriter (stream))
    {
        using (BinaryReader br = new BinaryReader(responseStream))
        {
            fileContentsLength = br.Read(fileContents, 0, fileContentsLength);
            while (fileContentsLength > 0)
            {
                fileContentsLength = br.Read(fileContents, 0, fileContentsLength);
                bw.Write(fileContents);
                fileContents = new byte[fileContentsLength];
            }
        }
 
    }
}
profile
주니어 개발자 기술노트

0개의 댓글