본문 바로가기
Programming/C#

[Unity, C#] FTP 다운로드, 업로드 하기

by 타임박스 2022. 4. 21.
반응형


✔ C# - FTP Download, Upload 



안녕하세요. 

Unity에서 FTP로 파일을 다운로드하거나 업로드하기 위한 방법입니다.

Unity에서 어차피 .Net을 사용하기에 C# API를 사용하는 것과 같습니다.

FTP API를 사용하고 파일을 쓰기 위해 아래 네임스페이스를 추가한다.

using System.Net;
using System.IO;

 

● FTP 파일 다운로드 예제

 public static string DownloadFile(string ftpPath, string FileNameToDownload,
                    string userName, string password, string tempDirPath)
{
    string ResponseDescription = "";
    string PureFileName = new FileInfo(FileNameToDownload).Name;
    string DownloadedFilePath = tempDirPath + "/" + PureFileName;
    string downloadUrl = string.Format("{0}/{1}", ftpPath, FileNameToDownload);
    FtpWebRequest req = (FtpWebRequest)FtpWebRequest.Create(downloadUrl);
    req.Method = WebRequestMethods.Ftp.DownloadFile;
    
    //익명 로그인시 userName = "anonymous", password = ""
    req.Credentials = new NetworkCredential(userName, password);
    req.UseBinary = true;
    req.Proxy = null;
    try
    {
        FtpWebResponse response = (FtpWebResponse)req.GetResponse();
        Stream stream = response.GetResponseStream();
        byte[] buffer = new byte[2048];
        FileStream fs = new FileStream(DownloadedFilePath, FileMode.Create);
        int ReadCount = stream.Read(buffer, 0, buffer.Length);
        while (ReadCount > 0)
        {
            fs.Write(buffer, 0, ReadCount);
            ReadCount = stream.Read(buffer, 0, buffer.Length);
        }
        ResponseDescription = response.StatusDescription;
        fs.Close();
        stream.Close();
    }
    catch {}

    return ResponseDescription;
}

 

● FTP 파일 업로드 예제

public string UploadFile(string ftpPath, string fileName, string userName, string pwd, string
UploadDirectory = "")
{
    string PureFileName = new FileInfo(fileName).Name;
    string uploadPath = string.Format("{0}{1}/{2}", ftpPath, UploadDirectory, PureFileName);
    FtpWebRequest req = (FtpWebRequest)WebRequest.Create(uploadPath);
    req.Proxy = null;
    req.Method = WebRequestMethods.Ftp.UploadFile;
    req.Credentials = new NetworkCredential(userName, pwd);
    req.UseBinary = true;
    req.UsePassive = true;

    byte[] data = File.ReadAllBytes(fileName);
    req.ContentLength = data.Length;
    Stream stream = req.GetRequestStream();
    stream.Write(data, 0, data.Length);

    stream.Close();

    FtpWebResponse res = (FtpWebResponse)req.GetResponse();
    return res.StatusDescription;
}

 

출처 : https://www.c-sharpcorner.com/UploadFile/kirtan007/download-upload-binary-files-on-ftp-server-using-C-Sharp/​

반응형

댓글