Thursday, September 17, 2009

FTPS in C# (using Chilkat FTP2)

之前(因為拖稿很久,所以是八百年前了)說過前陣子手上有個案子,需要將產出的檔案壓成ZIP再用FTPS送出,在C#下將檔案壓成ZIP檔之前有說了,現在來說怎麼使用FTPS(Implicit SSL)在C#下去送出資料。

老實說,因為那時候專案很趕,所以預計只花一天的時間解決ZIP+FTPS的問題,於是在時間不夠自己寫的情況下,就要找現成的方案了,那時候找了很多個FTPS solution,可是試了都失敗,後來試Chilkat的元件可以用,使用上也蠻方便的,於是就決定用這個了,Chilkat的元件都可以試用30天,公司位於美國芝加哥(如果我沒記錯),可以線上開發票,所以如果是公司要用也不愁沒發票報帳。

要用FTPS(Implicit SSL)是要用Chilkat的FTP2元件,我是抓.NET版的,他們家的元件都有各種語言的版本,感覺上技術力很強XD。

Chilkat網站上也有如何用FTPS(Implicit SSL)連線的範例,下面我也把我連線並上傳檔案的範例貼出來,如果剛好有人要做同樣的事,又是用C#開發,就直接貼過去吧XD




protected static void FTPS()
{
string Vendor = "1234567890";
string sDateTime = DateTime.Now.AddDays(-1).ToString("yyyyMMdd");
string fid1 = Vendor.Substring(0, 8) + "01." + sDateTime;
string fid2 = Vendor.Substring(0, 8) + "01." + sDateTime + ".FILEOK";

Chilkat.Ftp2 ftp = new Chilkat.Ftp2();

bool success;

success = ftp.UnlockComponent("你的啟動碼");
if (success != true)
{
Console.WriteLine(ftp.LastErrorText);
return;
}

ftp.Hostname = "ftp.secureftp-test.com";
ftp.Username = "test";
ftp.Password = "test";
ftp.Port = 990;

// We don't want AUTH SSL:
ftp.AuthTls = false;

// We want Implicit SSL:
ftp.Ssl = true;

// The default data transfer mode is "Active" as opposed to "Passive".
// Change it to Passive by setting the Passive property:
ftp.Passive = true;

// Connect and login to the FTP server.
success = ftp.Connect();
if (success != true)
{
Console.WriteLine(ftp.LastErrorText);
return;
}
else
{
Console.WriteLine(ftp.LastErrorText);
}

Console.WriteLine("FTPS Channel Established!");

//連線成功後,列出目前的檔案跟資料夾
// Do whatever you're doing to do ...
// upload files, download files, etc...

// The ListPattern property is our directory listing filter.
// The default value is "*", which includes everything.
Console.WriteLine(ftp.ListPattern);

// To get file and sub-directory information, simply
// loop from 0 to ftp.NumFilesAndDirs - 1
int i;
int n;
n = ftp.NumFilesAndDirs;
if (n < 0)
{
Console.WriteLine(ftp.LastErrorText);
return;
}

if (n > 0)
{
for (i = 0; i <= n - 1; i++)
{
// 顯示檔名跟檔案大小
Console.WriteLine(i + " " + ftp.GetFilename(i) + "\t" + ftp.GetSize(i));

// 如果是子目錄加說明
if (ftp.GetIsDirectory(i) == true)
{
Console.WriteLine(".. this is a sub-directory");
}
}
}

Console.WriteLine("-----------------------------------");

//因為要上傳兩個檔案,所以我傳兩次,懶得用全部上傳
// Upload file1.
success = ftp.PutFile(fid1, fid1);

if (success != true)
{
Console.WriteLine(ftp.LastErrorText);
return;
}
else
{
Console.WriteLine("File " + fid1 + " Uploaded!");
}

// Upload file2.
success = ftp.PutFile(fid2, fid2);

if (success != true)
{
Console.WriteLine(ftp.LastErrorText);
return;
}
else
{
Console.WriteLine("File " + fid2 + " Uploaded!");
}

ftp.Disconnect();
Console.WriteLine("FTPS Disconnect!");

}

No comments:

Post a Comment