반응형
FTP file download
FTP 접속하여 파일을 내려받는 코드는 다음만 있으면 된다.
Uri ftpUri = new Uri(strDownloadPath);
using (WebClient wc = new WebClient())
{
wc.BaseAddress = strDownloadPath;
wc.Credentials = new NetworkCredential(_ftpUser, _ftpPassword);
wc.DownloadFileAsync(ftpUri, downloadPath);//비동기
wc.DownloadFile(ftpUri, localPath);//동기
}
아래 코드는 응용 코드.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Net;
using System.ComponentModel;
using System.Windows.Forms;
public class FTPAccess
{
protected string _ftpURL;
protected string _ftpUser;
protected string _ftpPassword;
protected string _localPath;
protected long _fileSize;
protected Action actionMsg;
protected Action actionProgress;
protected string _targetPath;
protected string _fileName;
public FTPAccess(string ftpUrl, string ftpUser, string ftpPassword, string localPath, Action actionMsg, Action actionProgress)
{
this._ftpURL = ftpUrl;
this._ftpUser = ftpUser;
this._ftpPassword = ftpPassword;
this._localPath = localPath;
this.actionMsg = actionMsg;
this.actionProgress = actionProgress;
}
public void SingleDownload(string sourcePath, string targetPath, string fileName)
{
this._targetPath = targetPath;
this._fileName = fileName;
string strDownloadPath = string.Format(@"ftp:////", _ftpURL, sourcePath, fileName);
Uri ftpUri = new Uri(strDownloadPath);
using (WebClient wc = new WebClient())
{
actionMsg(string.Format(" Access : ftp://", DateTime.Now.ToString(), _ftpURL));
// 파일 사이즈
FtpWebRequest reqFtp = (FtpWebRequest)WebRequest.Create(ftpUri);
reqFtp.Method = WebRequestMethods.Ftp.GetFileSize;
reqFtp.Credentials = new NetworkCredential(_ftpUser, _ftpPassword);
FtpWebResponse resFtp = (FtpWebResponse)reqFtp.GetResponse();
_fileSize = resFtp.ContentLength;
resFtp.Close();
actionMsg(string.Format(" Login : ", DateTime.Now.ToString(), _ftpUser));
actionMsg(string.Format(" Download FIle : ", DateTime.Now.ToString(), fileName));
actionMsg(string.Format(" FileSize : ", DateTime.Now.ToString(), _fileSize.ToString("#,##0")));
actionMsg(string.Format(" Download Start.", DateTime.Now.ToString()));
wc.BaseAddress = strDownloadPath;
wc.Credentials = new NetworkCredential(_ftpUser, _ftpPassword);
wc.DownloadProgressChanged += new DownloadProgressChangedEventHandler(wc_DownloadProgressChanged);
wc.DownloadFileCompleted += new AsyncCompletedEventHandler(wc_DownloadFileCompleted);
//폴더 없으면 생성
if(!Directory.Exists(_localPath + "\\" + targetPath))
Directory.CreateDirectory(_localPath + "\\" + targetPath);
//파일 존재하면 삭제(안해도됨.)
string downloadPath = string.Format(@"\\", _localPath, targetPath, fileName);
if (File.Exists(downloadPath))
File.Delete(downloadPath);
wc.DownloadFileAsync(ftpUri, downloadPath);
}
}
//다운로드가 완료되었을 때
void wc_DownloadFileCompleted(object sender, AsyncCompletedEventArgs e)
{
try
{
actionMsg(string.Format(" Complete.", DateTime.Now.ToString()));
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
actionMsg(string.Format(" Error : ", DateTime.Now.ToString(), ex.Message));
}
}
//다운로드 중간중간에
void wc_DownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e)
{
int value = Convert.ToInt32((Convert.ToDouble(e.BytesReceived) / Convert.ToDouble(_fileSize)) * 100);
actionProgress(value);
}
}
public void FolderDownload(string sourcePath, string targetPath)
{
this._targetPath = targetPath;
string strDownloadPath = string.Format(@"ftp:///", _ftpURL, sourcePath);
Uri ftpUri = new Uri(strDownloadPath);
using (WebClient wc = new WebClient())
{
Console.Write(string.Format(" Access : ftp://\n", DateTime.Now.ToString(), _ftpURL));
// 파일 사이즈
FtpWebRequest reqFtp = (FtpWebRequest)WebRequest.Create(ftpUri);
reqFtp.Method = WebRequestMethods.Ftp.ListDirectory;
reqFtp.Credentials = new NetworkCredential(_ftpUser, _ftpPassword);
FtpWebResponse resFtp = (FtpWebResponse)reqFtp.GetResponse();
Stream responseStream = resFtp.GetResponseStream();
StreamReader reader = new StreamReader(responseStream);
Console.Write(string.Format(" Login : \n", DateTime.Now.ToString(), _ftpUser));
//Console.Write(string.Format(" Download FIle : ", DateTime.Now.ToString(), fileName));
Console.Write(string.Format(" Download Start.\n", DateTime.Now.ToString()));
wc.BaseAddress = strDownloadPath;
wc.Credentials = new NetworkCredential(_ftpUser, _ftpPassword);
wc.DownloadFileCompleted += new AsyncCompletedEventHandler(wc_DownloadFileCompleted);
//폴더 없으면 생성
if (!Directory.Exists(_localPath + "\\" + targetPath))
Directory.CreateDirectory(_localPath + "\\" + targetPath);
string line = reader.ReadLine();
string downloadPath = string.Empty;
while (line != null)
{
downloadPath = string.Format(@"\\", _localPath, targetPath, line.Replace(@"TestFile/", ""));
if (File.Exists(downloadPath))
File.Delete(downloadPath);
wc.DownloadFile(ftpUri + "/" + line.Replace(@"TestFile/", ""), downloadPath);
Console.Write(string.Format(" Download FIle : \n", DateTime.Now.ToString(), line.Replace(@"TestFile/", "")));
line = reader.ReadLine();
}
reader.Close();
resFtp.Close();
}
}
반응형
'C#' 카테고리의 다른 글
byte로 파일 읽기 (0) | 2015.12.29 |
---|---|
시스템 시작 혹은 중간에 강제로 디버깅 하고 싶을 때 (0) | 2015.12.24 |
text file에 텍스트 추가하기(File.AppendText) (0) | 2015.12.23 |
Stopped working CLR20r3 error (1) | 2015.12.22 |
Application.DoEvents() (0) | 2015.11.04 |
댓글