Skip to content

Instantly share code, notes, and snippets.

@ksasao
Last active November 15, 2015 00:51
Show Gist options
  • Save ksasao/ce83b8773f9d391b1e18 to your computer and use it in GitHub Desktop.
Save ksasao/ce83b8773f9d391b1e18 to your computer and use it in GitHub Desktop.
指定したフォルダにあるファイルをZIPで固めて定期的にアップロードするコード。
using System;
using System.Collections.Generic;
using System.IO;
using System.IO.Compression;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
namespace Mpga.IO
{
/// <summary>
/// 指定したフォルダ内のファイルを自動的にアップロードします
/// </summary>
public class AutoZipUpload
{
private System.Timers.Timer timer;
private string logFile = @"log.txt";
/// <summary>
/// 送信先URL
/// </summary>
public string SendUrl { get; set; }
/// <summary>
/// ユーザ名
/// </summary>
public string UserName { get; set; }
/// <summary>
/// パスワード
/// </summary>
public string Password { get; set; }
/// <summary>
/// 送信元のファイルがあるパス
/// </summary>
public string Path { get; set; }
// ファイルのパターン
public string Pattern {get; set;}
/// <summary>
/// 最終更新時刻からアップロード対象に含めるまでの時間(秒)
/// </summary>
public int UploadWaiting { get; set; }
/// <summary>
/// ファイルのアップロード間隔(秒)
/// </summary>
public int UploadInterval { get { return uploadInterval;} set { SetInterval(value); } }
private int uploadInterval;
public AutoZipUpload(string sendUrl, string userName, string password, string path, string pattern)
{
Initialize(sendUrl, userName, password, path, pattern);
}
private void Initialize(string sendUrl, string userName, string password, string path, string pattern)
{
this.SendUrl = sendUrl;
this.UserName = userName;
this.Password = password;
this.Path = path;
this.Pattern = pattern;
this.timer = new System.Timers.Timer();
this.UploadWaiting = 80 * 60;
this.UploadInterval = 5 * 60;
this.timer.Enabled = true;
this.timer.AutoReset = true;
this.timer.Elapsed += timer_Elapsed;
}
private void SetInterval(int interval){
this.uploadInterval = interval;
this.timer.Interval = this.uploadInterval * 1000;
}
private bool IsTargetFile(string filename)
{
return File.GetLastWriteTime(filename).AddSeconds(this.UploadWaiting) < DateTime.Now;
}
/// <summary>
/// 定期的に実行されるタスク
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
void timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
{
this.timer.Stop();
Upload();
this.timer.Start();
}
/// <summary>
/// ファイルアップロードタスクを開始します
/// </summary>
public void Start()
{
this.timer.Start();
Log("Timer started.");
Upload();
}
/// <summary>
/// ファイルアップロードタスクを停止します
/// </summary>
public void Stop()
{
this.timer.Stop();
Log("Timer stopped.");
}
public void Upload()
{
// ファイル一覧を取得
var files = Directory.EnumerateFiles(this.Path, this.Pattern, SearchOption.AllDirectories).ToArray();
if (files.Length == 0)
{
Log("No file found.");
return;
}
Log("Uploading started.");
foreach (var f in files)
{
// アップロード対象かどうかのチェック
if (!IsTargetFile(f))
{
Log("Upload pending: " + f);
continue;
}
UploadAsZipFile(f);
}
UploadLogFile();
Log("Uploading finished.");
}
private void UploadAsZipFile(string f)
{
try
{
string tempPath = System.IO.Path.GetTempPath() + @"AutoUpload\";
System.IO.Directory.CreateDirectory(tempPath);
string filename = System.IO.Path.GetFileName(f);
string zipname = filename + ".zip";
string destPath = tempPath + filename;
string zipfile = "temp.zip";
string testfile = "test.zip";
File.Delete(zipfile);
File.Copy(f, destPath, true);
using (WebClient wc = new WebClient())
{
ZipFile.CreateFromDirectory(tempPath, zipfile);
string target = this.SendUrl + @"/" + zipname;
wc.Credentials = new NetworkCredential(this.UserName, this.Password);
// 対象をアップロード
Log("Uploading: " + f);
wc.UploadFile(target, zipfile);
// 正しくアップロードされていることを確認するためにダウンロード
Log("Verifing: " + f);
wc.DownloadFile(target, testfile);
// 正しくアップロードされていたら対象を削除
bool isValid = CompareFile(zipfile, testfile);
if (isValid)
{
File.Delete(f);
Log("Removed: " + f);
}
Directory.Delete(tempPath, true);
}
}
catch (Exception ex)
{
Log(ex.Message);
}
}
private void UploadLogFile()
{
try
{
using (WebClient wc = new WebClient())
{
string target = this.SendUrl + @"/" + this.logFile;
wc.Credentials = new NetworkCredential(this.UserName, this.Password);
wc.UploadFile(target, logFile);
}
}
catch (Exception ex)
{
Log(ex.Message);
}
}
private bool CompareFile(string file1, string file2)
{
byte[] c1 = File.ReadAllBytes(file1);
byte[] c2 = File.ReadAllBytes(file2);
bool isValid = true;
if (c1.Length == c2.Length)
{
for (int i = 0; i < c1.Length; i++)
{
if (c1[i] != c2[i])
{
isValid = false;
break;
}
}
}
else
{
isValid = false;
}
return isValid;
}
public void Log(string data)
{
string contents = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "," + data +"\r\n";
File.AppendAllText(this.logFile, contents);
Console.Write(contents);
}
}
}
using Mpga.IO;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AutoUploadCmd
{
class Program
{
static void Main(string[] args)
{
string url = @"ftp://(アップロード先)";
string user = "(ユーザ名)";
string password = "(パスワード)";
string path = @"(アップロード対象のフォルダ)";
Task.Run(() =>
{
AutoZipUpload upload = new AutoZipUpload(url, user, password, path, "*");
upload.UploadWaiting = 60;
upload.Start();
});
Console.ReadKey();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment