반응형
1. 프로그램 자동 업그레이드 (Auto Checker)
프로그램을 진행하다 보면 항상 걸리는게 프로그램 버젼에 자동다운로드가 있었으면 한다.
웹 사이트 검색을 하다보면 많은 프로그램이 나와있지만 썩 맘에 들지 않아 하나 만들어 보았습니다.
1) 화면
2) 환경파일
3) 소스
1) 화면
사용 컴포넌트 >
- progressBar1 (ProgressBar)
- lblMsg (label)
- lbProgress (label)
2) 환경파일 (App.config)
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.7.2" />
</startup>
<appSettings>
<add key="conn_server" value="ftp://서버IP/포더" />
<add key="client_exec" value="패치후 실행파일" />
</appSettings>
</configuration>
3) 소스 (ver 1.0)
- 프로그램을 조금 수정해서 본인에 입맛에 맞게 사용하셔도 좋을것 같습니다.
- 버젼체크는 현재 PC에 있는 다운로드 날짜/시간과 FTP 업로드된 날짜/시간을 비교해서 DownLoad를 받습니다.
using System;
using System.ComponentModel;
using System.Configuration;
using System.IO;
using System.Linq;
using System.Net;
using System.Windows.Forms;
namespace AutoCheckerSync
{
public partial class AutoChecker : Form
{
private string txtServer = "ftp://", txtUser = "사용자ID", txtPassword = "암호";
private string txtPathClient = @"C:\폴더\", txtExecClient = "";
public AutoChecker()
{
InitializeComponent();
// config file read
txtServer = ConfigurationManager.AppSettings.Get("conn_server");
txtExecClient = ConfigurationManager.AppSettings.Get("client_exec");
txtPathClient = Application.StartupPath + "\\";
}
private void AutoChecker_Load(object sender, EventArgs e)
{
this.Show();
CheckUpdateList(txtServer, txtUser, txtPassword);
// 프로그램 실행
System.Diagnostics.Process ps = new System.Diagnostics.Process();
ps.StartInfo.FileName = txtPathClient + txtExecClient;
ps.Start();
this.Close();
}
private void CheckUpdateList(string agFtpServer, string agUser, string agPassword)
{
int count, total;
string fileName, fileExt;
try
{
//Optional
this.Text = "Connecting...";
Application.DoEvents();
//Create FTP request
FtpWebRequest request = FtpWebRequest.Create(agFtpServer) as FtpWebRequest;
request.Method = WebRequestMethods.Ftp.ListDirectory;
request.Credentials = new NetworkCredential(agUser, agPassword);
request.UsePassive = true;
request.UseBinary = true;
request.KeepAlive = false;
FtpWebResponse response = request.GetResponse() as FtpWebResponse;
Stream responseStream = response.GetResponseStream();
StreamReader reader = new StreamReader(responseStream);
//Read the server's response
this.Text = "Retrieving List...";
Application.DoEvents();
string strData = reader.ReadToEnd();
string[] filesInDirectory = strData.Split(new string[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries);
count = 0;
total = filesInDirectory.Count();
foreach (string file in filesInDirectory)
{
count++;
fileName = Path.GetFileName(file);
fileExt = Path.GetExtension(file);
if (GetFilesInfo(agFtpServer, agUser, agPassword, fileName) == true)
{
this.Text = "자동 업데이트 중 ... " + count.ToString() + "/" + total.ToString() + " (" + fileName + ")";
Application.DoEvents();
DownloadFiles(agFtpServer, agUser, agPassword, fileName);
}
}
this.Text = "자동 업데이트 완료.";
//Clean-up
reader.Close();
responseStream.Close(); //redundant
response.Close();
}
catch (Exception ex)
{
MessageBox.Show("There was an error connecting to the FTP Server" + ex.Message);
}
}
public bool GetFilesInfo(string agFtpServer, string agUser, string agPassword, string agFilename)
{
DateTime serverDate, clientDate;
try
{
// Server DateTime
FtpWebRequest reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(agFtpServer + "/" + agFilename));
reqFTP.UseBinary = true;
reqFTP.UsePassive = true;
reqFTP.Credentials = new NetworkCredential(agUser, agPassword);
reqFTP.Method = WebRequestMethods.Ftp.GetDateTimestamp;
FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
serverDate = response.LastModified;
response.Close();
// Client DateTime
FileInfo info = new FileInfo(txtPathClient + agFilename);
clientDate = info.LastWriteTime;
// DateTime Check
if (serverDate >= clientDate)
return true;
else
return false;
}
catch (Exception ex)
{ MessageBox.Show(ex.Message);
return false;
}
}
private void DownloadFiles(string agFtpServer, string agUser, string agPassword, string agFilename)
{
{
using (WebClient webClient = new WebClient())
{
webClient.Credentials = new NetworkCredential(agUser, agPassword);
try
{
webClient.DownloadFileCompleted += new AsyncCompletedEventHandler(client_DownloadFileCompleted);
webClient.DownloadProgressChanged += new DownloadProgressChangedEventHandler(client_DownloadProgressChanged);
webClient.DownloadFileAsync(new Uri(agFtpServer + "/" + agFilename), txtPathClient + agFilename);
}
catch (WebException ex)
{
MessageBox.Show(ex.Message, " ", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
}
private void client_DownloadFileCompleted(object sender, AsyncCompletedEventArgs e)
{
if (e.Error != null)
{
MessageBox.Show(e.Error.Message, " ", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
else
{
this.Text = "자동 업데이트 중 ... ";
}
}
private void client_DownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e)
{
// this.progressBar1.Minimum = 0;
this.progressBar1.Maximum = (int)e.TotalBytesToReceive;
this.progressBar1.Value = (int)e.BytesReceived;
this.lbProgress.Text = string.Format("{0} /{1} bytes {2}%",e.BytesReceived, e.TotalBytesToReceive, e.ProgressPercentage);
}
}
}
2. 마무리
프로그램 사용하시면 좋은 방법으로 수정하시고 사용하시면 좋겠습니다.
반응형
'개발(IT) > C#(VisualStudio)' 카테고리의 다른 글
[c#] MS-SQL 연동 Helper (0) | 2023.09.23 |
---|---|
[c#] 오라클(Oracle) 연동 Helper (0) | 2023.09.23 |
Visual Studio 2022 설치 순서 (0) | 2023.08.23 |