我写这个是为了检查表列中的文件名是否存在于 ftp 服务器目录中,如果存在,然后更新(使用更新查询)列 Isexists 的值,1
否则保持原样。
我正在使用 DataTable 读取每一行(文件名),然后一直使用 FtpWebRequest 来检查文件是否存在。
这样CheckIfFtpFileExists(string fileUri
)接听电话的次数等于没有。数据表中的行数。
有什么方法可以进行 FTP 身份验证。只有一次,然后调用该函数。
任何建议如何改进我的代码以提高速度。
namespace FTP_File_Check
{
class Program
{
static void Main(string[] args)
{
string connString = @"Integrated Security=SSPI;Persist Security Info=False;Initial Catalog=DMSTG;Data Source=.";
string sql = @"SELECT full_file_name from Intellitrack.S_Sr_att_Delta_Consolidated_28082012 where Isexists=0";
SqlConnection conn = new SqlConnection(connString);
conn.Open();
SqlDataAdapter da = new SqlDataAdapter(sql, conn);
DataTable dt = new DataTable();
da.Fill(dt);
foreach (DataRow row in dt.Rows)
{
foreach (DataColumn col in dt.Columns)
{
SqlConnection sqlConnection1 = new SqlConnection("Integrated Security=SSPI;Persist Security Info=False;Initial Catalog=DMSTG;Data Source=.");
SqlCommand cmd = new SqlCommand();
cmd.CommandType = CommandType.Text;
if (CheckIfFtpFileExists("ftp://myftpaddressgoeshere.com/0708/" + row[col].ToString()))
{
// Found File Exists
cmd.CommandText = @"UPDATE Intellitrack.S_Sr_att_Delta_Consolidated_28082012
SET Isexists = 1
where full_file_name='" + row[col].ToString() + "'";
cmd.Connection = sqlConnection1;
sqlConnection1.Open();
cmd.ExecuteNonQuery();
sqlConnection1.Close();
}
}
}
}
public static bool CheckIfFtpFileExists(string fileUri)
{
FtpWebRequest request = (FtpWebRequest)FtpWebRequest.Create(fileUri);
request.Credentials = new NetworkCredential("myuserid", "mypassword");
request.KeepAlive = true;
request.ConnectionGroupName = "file";
request.ServicePoint.ConnectionLimit = 8;
request.UseBinary = true;
request.UsePassive = false;
request.Method = WebRequestMethods.Ftp.ListDirectoryDetails;
try
{
FtpWebResponse response = (FtpWebResponse)request.GetResponse();
}
catch (WebException ex)
{
FtpWebResponse response = (FtpWebResponse)ex.Response;
if (FtpStatusCode.NotLoggedIn == response.StatusCode)
{
Console.WriteLine("Failed to connect to ftp server");
Console.ReadLine();
Environment.Exit(99);
}
else
{
if (FtpStatusCode.ActionNotTakenFileUnavailable == response.StatusCode)
{
return false;
}
}
}
return true;
}
}
}