如何组合我的FTP查询?

时间:2012-12-06 04:00:12

标签: c# ftp ftpwebrequest

我的程序多次查询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。请给出任何建议!

3 个答案:

答案 0 :(得分: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");
    }
}

答案 1 :(得分:1)

您可能需要查看WinSCP library。 WinSCP具有许多功能,并且支持比(本质上不安全的FTP)更安全的协议。 最近的版本甚至还有脚本机制。

答案 2 :(得分:0)

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