본문 바로가기

프로그램/유니티 네트워크

[유니티 네트워크] FTP(File Transfer Protocol)

728x90
반응형
using UnityEngine;
using System.Net;
using System.IO;

public class FTP : MonoBehaviour
{
    public string m_UserName = "id@site.com";
    public string m_Password = "abcde";

    void Update()
    {
        if (Input.GetKeyDown(KeyCode.U))
            FtpUpload();

        if (Input.GetKeyDown(KeyCode.D))
            FtpDownload();
    }

    void FtpUpload()
    {
        FtpWebRequest ftpWebRequest = (FtpWebRequest)WebRequest.Create("ftp://ftp.site.com/upload.txt");
        ftpWebRequest.Credentials = new NetworkCredential(m_UserName, m_Password);
        //ftpWebRequest.EnableSsl = true; // TLS/SSL
        ftpWebRequest.UseBinary = false;   // ASCII, Binary(디폴트)
        ftpWebRequest.Method = WebRequestMethods.Ftp.UploadFile;
                
        byte[] data = File.ReadAllBytes(@"D:\upload.txt");

        using (var ftpStream = ftpWebRequest.GetRequestStream())
        {
            ftpStream.Write(data, 0, data.Length);
        }
                
        using (var response = (FtpWebResponse)ftpWebRequest.GetResponse())
        {
            Debug.Log(response.StatusDescription);
        }
    }

    void FtpDownload()
    {
        FtpWebRequest ftpWebRequest = (FtpWebRequest)WebRequest.Create("ftp://ftp.site.com/download.txt");
        ftpWebRequest.Credentials = new NetworkCredential(m_UserName, m_Password);
        ftpWebRequest.Method = WebRequestMethods.Ftp.DownloadFile;

        using (var localfile = File.Open(@"D:\download.txt", FileMode.Create))
        using (var ftpStream = ftpWebRequest.GetResponse().GetResponseStream())
        {
            byte[] buffer = new byte[1024];
            int n;
            while ((n = ftpStream.Read(buffer, 0, buffer.Length)) > 0)
            {
                localfile.Write(buffer, 0, n);
            }
        }
    }
}
728x90
반응형