★★★★★★HTTP Download★★★★★★
private void downloadData(string url)
{
progressBar1.Value = 0;
downloadedData = new byte[0];
try
{
//Optional
this.Text = "Connecting...";
Application.DoEvents();
//Get a data stream from the url
WebRequest req = WebRequest.Create(url);
WebResponse response = req.GetResponse();
Stream stream = response.GetResponseStream();
//Download in chuncks
byte[] buffer = new byte[1024];
//Get Total Size
int dataLength = (int)response.ContentLength;
//With the total data we can set up our progress indicators
progressBar1.Maximum = dataLength;
lbProgress.Text = "0/" + dataLength.ToString();
this.Text = "Downloading...";
Application.DoEvents();
//Download to memory
//Note: adjust the streams here to download directly to the hard drive
MemoryStream memStream = new MemoryStream();
while (true)
{
//Try to read the data
int bytesRead = stream.Read(buffer, 0, buffer.Length);
if (bytesRead == 0)
{
//Finished downloading
progressBar1.Value = progressBar1.Maximum;
lbProgress.Text = dataLength.ToString() + "/" + dataLength.ToString();
Application.DoEvents();
break;
}
else
{
//Write the downloaded data
memStream.Write(buffer, 0, bytesRead);
//Update the progress bar
if (progressBar1.Value + bytesRead <= progressBar1.Maximum)
{
progressBar1.Value += bytesRead;
lbProgress.Text = progressBar1.Value.ToString() + "/" + dataLength.ToString();
progressBar1.Refresh();
Application.DoEvents();
}
}
}
//Convert the downloaded stream to a byte array
downloadedData = memStream.ToArray();
//Clean up
stream.Close();
memStream.Close();
}
★★★★FTP Download★★★★
public void Download(string ftpDirectoryName, string downFileName, string localPath, ProgressBar progressBar, bool showCompleted)
{
try
{
this.progressBar = progressBar;
Uri ftpUri = new Uri(hostName + "/" + ftpDirectoryName + "/" + downFileName);
// 파일 사이즈
FtpWebRequest reqFtp = (FtpWebRequest)WebRequest.Create(ftpUri);
reqFtp.Method = WebRequestMethods.Ftp.GetFileSize;
reqFtp.Credentials = new NetworkCredential(userName, password);
FtpWebResponse resFtp = (FtpWebResponse)reqFtp.GetResponse();
fileSize = resFtp.ContentLength;
resFtp.Close();
using (WebClient request = new WebClient())
{
request.Credentials = new NetworkCredential(userName, password);
request.DownloadProgressChanged += request_DownloadProgressChanged;
// 다운로드가 완료 된 후 메시지 보이기
if (showCompleted)
{
request.DownloadFileCompleted += request_DownloadFileCompleted;
}
// 다운로드 시작
request.DownloadFileAsync(ftpUri, @localPath + "/" + downFileName);
}
}
catch (Exception e)
{
MessageBox.Show(e.ToString());
}
}
'C#' 카테고리의 다른 글
[C#]Create a Custom Image Button Control (0) | 2013.03.19 |
---|---|
[C#] 인터넷 연결 확인 API (0) | 2013.03.05 |
[C#] 마우스 좌표 구하기 (0) | 2013.02.07 |
[C#] 버전 정보 및 컴파일(Build) 날짜 정보 구하기 (0) | 2013.02.05 |
[C#] 숫자만 추출 (0) | 2013.02.02 |