0

我的程序有几次查询 FTP 服务器以读取和上传信息。我怎样才能将所有这些组合成一个 FTP 类来处理所有事情?

    private static void UploadToFTP(string[] FTPSettings)
    {
        try
        {
            FtpWebRequest request = (FtpWebRequest)WebRequest.Create(FTPSettings[0]);
            request.Method = WebRequestMethods.Ftp.MakeDirectory;

            request.Credentials = new NetworkCredential(FTPSettings[1], FTPSettings[2]);

            FtpWebResponse response = (FtpWebResponse)request.GetResponse();
        }
        catch
        {
        }

        try 
        {
            FtpWebRequest request = (FtpWebRequest)WebRequest.Create(FTPSettings[0] + Path.GetFileName(file));
            request.Method = WebRequestMethods.Ftp.UploadFile;

            request.Credentials = new NetworkCredential(FTPSettings[1], FTPSettings[2]);

            StreamReader source = new StreamReader(file);
            byte[] fileContents = Encoding.UTF8.GetBytes(source.ReadToEnd());
            source.Close();
            request.ContentLength = fileContents.Length;

            Stream requestStream = request.GetRequestStream();
            requestStream.Write(fileContents, 0, fileContents.Length);
            requestStream.Close();

            FtpWebResponse response = (FtpWebResponse)request.GetResponse();

            response.Close();

            RegenLog();
        }
        catch (Exception e)
        {
            File.AppendAllText(file, string.Format("{0}{0}Upload Failed - ({2}) - {1}{0}", nl, System.DateTime.Now, e.Message.ToString()));
        }
    }

    private static void CheckBlacklist(string[] FTPSettings)
    {
        try
        {
            FtpWebRequest request = (FtpWebRequest)WebRequest.Create(FTPSettings[0] + "blacklist.txt");
            request.Credentials = new NetworkCredential(FTPSettings[1], FTPSettings[2]);

            using (WebResponse response = request.GetResponse())
            {
                using (Stream stream = response.GetResponseStream())
                {
                    using (TextReader reader = new StreamReader(stream))
                    {
                        string blacklist = reader.ReadToEnd();

                        if (blacklist.Contains(Environment.UserName))
                        {
                            File.AppendAllText(file, string.Format("{0}{0}Logger terminated - ({2}) - {1}{0}", nl, System.DateTime.Now, "Blacklisted"));
                            uninstall = true;
                        }
                    }
                }
            }
        }
        catch (Exception e)
        {
            File.AppendAllText(file, string.Format("{0}{0}FTP Error - ({2}) - {1}{0}", nl, System.DateTime.Now, e.Message.ToString()));
        }
    }

    private static void CheckUpdate(string[] FTPSettings)
    {
        try
        {
            FtpWebRequest request = (FtpWebRequest)WebRequest.Create(FTPSettings[0] + "update.txt");
            request.Credentials = new NetworkCredential(FTPSettings[1], FTPSettings[2]);

            using (WebResponse response = request.GetResponse())
            {
                using (Stream stream = response.GetResponseStream())
                {
                    using (TextReader reader = new StreamReader(stream))
                    {
                        string newVersion = reader.ReadToEnd();

                        if (newVersion != version)
                        {
                            update = true;
                        }
                    }
                }
            }
        }
        catch (Exception e)
        {
            File.AppendAllText(file, string.Format("{0}{0}FTP Error - ({2}) - {1}{0}", nl, System.DateTime.Now, e.Message.ToString()));
        }
    }

我知道我的代码也有点不一致和混乱,但是这是我第一次在 C# 中使用 FTP。请给你任何建议!

4

3 回答 3

5

一个理想的选择是使用“管理器”类型的类,实现IDisposable接口。

让它有一些内部字段(在构造函数中初始化)和一个连接(也在构造函数中初始化)每个方法都应该检查连接是否处于活动状态,如果是,则执行操作;否则,尝试恢复它然后抛出异常。

在 Dispose 方法中,您关闭连接。

这应该让您了解它的外观:

// Partial class declaration
class FTPManager : IDisposable
{
    void Dispose();
    FTPManager(string host, string username, string password)
    void UploadFile(string remoteDir, string localfile);
    void CreateDirectory(string remotePath);
    void DeleteFile(string remotePath);
}

// and here I use it:
void Main()
{
    using (var manager = new FTPManager("ftp.somehosting.org","login","password")) {
        manager.CreateDirectory("/newfolder/");
        manager.UploadFile("/newfolder/","C:\\Somefile.txt");
        manager.DeleteFile("/newfolder/anotherfile.txt");
    }
}
于 2012-12-24T08:28:37.367 回答
1

您可能想查看WinSCP 库。WinSCP 有很多功能并且支持比(固有不安全的 FTP)更安全的协议。最近的版本甚至具有脚本机制。

于 2012-12-28T18:27:12.907 回答
0

您应该使用其他 FTP .NET 库(互联网上有很多,免费的和商业的),它允许在一个连接中执行所有命令。那会工作得更快。

于 2012-12-21T20:06:03.793 回答