前回、IIS7.5 で FTPSの設定を行いましたので、今回はC#から接続してファイル一覧を取得します。
参考サイト:
DOBON.NET - FtpWebRequest、FtpWebResponseクラスを使ってFTPサーバーにアクセスする。
http://dobon.net/vb/dotnet/internet/ftpwebrequest.html
上記サイトの「FTPサーバーのディレクトリのファイル一覧を取得する」に2箇所ほどコードを追加します。
1.今回は自己署名証明書(信頼できない証明書)を使用していますので、ServerCertificateValidationCallback で常にTrue(正常)を返すようにします。
ServicePointManager.ServerCertificateValidationCallback =
new RemoteCertificateValidationCallback(
delegate(Object certsender, X509Certificate certificate, X509Chain chain,
SslPolicyErrors sslPolicyErrors) { return true; });
2.SSL 接続を使用しますので、FtpWebRequest.EnableSsl プロパティ に True を設定します。
ftpReq.EnableSsl = true;
これで完成です。修正後のコードは下記のようになります。
using System;
using System.Net;
using System.IO;
using System.Net.Security;
using System.Security.Cryptography.X509Certificates;
namespace FTPS
{
class Program
{
static void Main(string[] args)
{
ServicePointManager.ServerCertificateValidationCallback =
new RemoteCertificateValidationCallback(
delegate(Object certsender, X509Certificate certificate, X509Chain chain,
SslPolicyErrors sslPolicyErrors) { return true; });
FtpWebRequest ftpReq = (FtpWebRequest) FtpWebRequest.Create("ftp://localhost");
ftpReq.EnableSsl = true;
ftpReq.Credentials = new System.Net.NetworkCredential("FTPDemo", "hoge");
ftpReq.Method = WebRequestMethods.Ftp.ListDirectory;
ftpReq.KeepAlive = false;
FtpWebResponse ftpRes = (FtpWebResponse)ftpReq.GetResponse();
StreamReader sr = new StreamReader(ftpRes.GetResponseStream());
string res = sr.ReadToEnd();
Console.WriteLine(res);
sr.Close();
Console.WriteLine("{0}: {1}", ftpRes.StatusCode, ftpRes.StatusDescription);
ftpRes.Close();
Console.ReadLine();
}
}
}