본문 바로가기
C#

FTP에 파일 올리기

by 캡틴노랑이 2017. 6. 4.
반응형
기본 템플릿은 다음과 같다.
다음 소스에서 필요한 부분만 응용을 하면된다. 
보통 파일 경로, 파일의 개수등일 것이다.
 

//using System.Net; string ftpPath = "ftp://192.168.18.5/Upload/info/test.txt"; string user = "ftpuser"; string password = "password"; string sendFile = string.Format(@"C:\{0}.txt", DateTime.Today.ToString("yyyyMMdd hh:mm:ss"); FtpWebRequest fwr = (FtpWebRequest)WebRequest.Create(ftpPath); fwr.Method = WebRequestMethods.Ftp.UploadFile; fwr.Credentials = new NetworkCredential(user, password); byte[] data; using (StreamReader reader = new StreamReader(sendFile)) { data = Encoding.UTF8.GetBytes(reader.ReadToEnd()); } fwr.ContentLength = data.Length; using (Stream reqStream = fwr.GetRequestStream()) { reqStream.Write(data, 0, data.Length); }


간단한 응용

파일을 보내느 것이 아니라 특정 정보를 프로그램에서 생성(메모리 스트림, 텍스트 등)보낼 때

아래는 텍스트를 생성후 해당 텍스트를 로컬에 파일로 떨구듯이, ftp 올리는 예제이다


//using System.Net;
string sendData = "test";
Uri ftpUri = new Uri(strDownloadPath);
string ftpPath = string.Format(@"ftp://192.168.18.5/Upload/info/{0}.txt", DateTime.Now.ToString("yyyyMMdd-hhmmss"));
string user = "ftpuser";
string pwd = "password";
//string inputFile = string.Format(@"C:\Work\Dixon\Secret\TestSecret\{0}.txt", DateTime.Today.ToString("yyyyMMdd hh:mm:ss"));


FtpWebRequest req = (FtpWebRequest)WebRequest.Create(ftpPath);

req.Method = WebRequestMethods.Ftp.UploadFile;

req.Credentials = new NetworkCredential(user, pwd);


byte[] buffer = Encoding.UTF8.GetBytes(sendData);

req.ContentLength = buffer.Length;
using (Stream reqStream = req.GetRequestStream())
{
    reqStream.Write(buffer, 0, buffer.Length);
}


반응형

댓글