Filezilla Server、c#、FTP
近來自身有個小需求,需要從主機的指定目錄中定時取得最新更新的一個檔案透過FTP傳回來,用一般的自動備份軟體似乎沒法
自動抓最新的檔案備份,於是就想利用C#內建的FTP上傳類別實現~
但實測過程中發現用外部IP怎麼測都不成功,換localhost就成功了,檢查過防火牆,路由器設定等都沒問題,後來亂試的過程中因我的ftp server 是用 filezilla,發現只要如下圖被我紅色塗掉的地方填入外部ip即可(預設Default),且沒改前用 filezilla Client也不行,奇怪以前好像不用設這個,不曉得是否太久沒用記錯還是後來改版有差,特此記錄一下
class Program
{
static void Main(string[] args)
{
DirectoryInfo dirfo = new DirectoryInfo(@"d:\xxxx");
FileInfo[] files = dirfo.GetFiles("*.*", SearchOption.TopDirectoryOnly);
//todo..取得的檔案依指定條件排序,MyDateSorter方法裡我是寫依檔案修改時間排序,因我要抓時間最新的一個檔案
Array.Sort(files, new MyDateSorter());
//todo...取得修改時間最後的一個檔案
string LastFileName = files[files.Count() - 1].FullName;
Console.WriteLine(LastFileName + " , " + files[files.Count() - 1].LastWriteTime);
foreach (var item in files)
{
Console.WriteLine(item.FullName + " , " + item.LastWriteTime);
}
// Get the object used to communicate with the server.
//todo..Create後指定ftp位置及上傳後的檔案名稱(可另指定不同名稱)
FtpWebRequest request = (FtpWebRequest)WebRequest.Create("ftp://xxx.xxx.xxx.xxx/完整檔名");
request.Method = WebRequestMethods.Ftp.UploadFile;
request.Timeout = 5000000; //todo..設定timeout ,單位毫秒
request.Proxy = null; //todo..網路上有人說這個預設會找Proxy,速度很慢
request.UseBinary = true; //todo..指定檔案傳輸資料型別
request.UsePassive = true; //todo..被動模式,bool值
// This example assumes the FTP site uses anonymous logon.
request.Credentials = new NetworkCredential("ftp帳號", "ftp密碼");
// Copy the contents of the file to the request stream.取得要上傳檔案的FileStream並指定檔案開啟及讀取
//FileStream sourceStream = new System.IO.FileStream(@"D:\xxxx\完整檔名", System.IO.FileMode.Open, System.IO.FileAccess.Read);
FileStream sourceStream = File.Open(@"D:\xxxx\完整檔名", System.IO.FileMode.Open, System.IO.FileAccess.Read);
try
{
BinaryReader br = new System.IO.BinaryReader(sourceStream);
byte[] fileContents = br.ReadBytes(Convert.ToInt32(sourceStream.Length));
sourceStream.Close();
//request.ContentLength = fileContents.Length;
Stream requestStream = request.GetRequestStream();
requestStream.Write(fileContents, 0, fileContents.Length);
requestStream.Close();
FtpWebResponse response = (FtpWebResponse)request.GetResponse();
Console.WriteLine("Upload File Complete, status {0}", response.StatusDescription);
response.Close();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
}
public class MyDateSorter : IComparer
{
#region IComparer Members
public int Compare(object x, object y)
{
if (x == null && y == null)
{
return 0;
}
if (x == null)
{
return -1;
}
if (y == null)
{
return 1;
}
FileInfo xInfo = (FileInfo)x;
FileInfo yInfo = (FileInfo)y;
//依名稱排序
//return xInfo.FullName.CompareTo(yInfo.FullName);//遞增
//return yInfo.FullName.CompareTo(xInfo.FullName);//遞減
//依修改日期排序
return xInfo.LastWriteTime.CompareTo (yInfo.LastWriteTime);//遞增
//return yInfo.LastWriteTime.CompareTo(xInfo.LastWriteTime);//遞減
}
#endregion