C#使用FTP上传整个目录

时间:2012-11-09 16:26:23

标签: c# recursion upload ftp directory

我要做的是在C#(C Sharp)中使用FTP上传网站。所以我需要上传文件夹中的所有文件和文件夹,保持其结构。我正在使用此FTP类:http://www.codeproject.com/Tips/443588/Simple-Csharp-FTP-Class进行实际上传。

我得出结论,我需要编写一个递归方法,遍历主目录的每个子目录并上传其中的所有文件和文件夹。这应该将我的文件夹的精确副本复制到FTP。问题是......我不知道怎么写这样的方法。我以前写过递归方法,但我是FTP部分的新手。

这是我到目前为止所做的:

private void recursiveDirectory(string directoryPath)
    {
        string[] filePaths = null;
        string[] subDirectories = null;

        filePaths = Directory.GetFiles(directoryPath, "*.*");
        subDirectories = Directory.GetDirectories(directoryPath);

        if (filePaths != null && subDirectories != null)
        {
            foreach (string directory in subDirectories)
            {
                ftpClient.createDirectory(directory);
            }
            foreach (string file in filePaths)
            {
                ftpClient.upload(Path.GetDirectoryName(directoryPath), file);
            }
        }
    }

但它远未完成,我不知道如何继续。我确定比我更需要知道这一点!在此先感谢:)

哦......如果它报告了它的进展会很好:)(我正在使用进度条)

编辑: 可能一直不清楚......如何使用FTP上传包含所有子目录和文件的目录?

4 个答案:

答案 0 :(得分:14)

解决了问题! :)

好吧,所以我设法编写了myslef方法。如果有人需要,请随意复制:

private void recursiveDirectory(string dirPath, string uploadPath)
    {
        string[] files = Directory.GetFiles(dirPath, "*.*");
        string[] subDirs = Directory.GetDirectories(dirPath);

        foreach (string file in files)
        {
            ftpClient.upload(uploadPath + "/" + Path.GetFileName(file), file);
        }

        foreach (string subDir in subDirs)
        {
            ftpClient.createDirectory(uploadPath + "/" + Path.GetFileName(subDir));
            recursiveDirectory(subDir, uploadPath + "/" + Path.GetFileName(subDir));
        }
    }

效果很好:)

答案 1 :(得分:4)

我编写了一个FTP classe并将其包装在WinForms用户控件中。您可以在文章An FtpClient Class and WinForm Control中查看我的代码。

答案 2 :(得分:2)

我编写了一个可重用的类,将整个目录上传到Windows服务器上的ftp site
该程序还重命名了该文件夹的旧版本(我使用它将Windows服务程序上传到服务器上)。 也许有些需要这个:

class MyFtpClient
{
    protected string FtpUser { get; set; }
    protected string FtpPass { get; set; }
    protected string FtpServerUrl { get; set; }
    protected string DirPathToUpload { get; set; }
    protected string BaseDirectory { get; set; }

    public MyFtpClient(string ftpuser, string ftppass, string ftpserverurl, string dirpathtoupload)
    {
        this.FtpPass = ftppass;
        this.FtpUser = ftpuser;
        this.FtpServerUrl = ftpserverurl;
        this.DirPathToUpload = dirpathtoupload;
        var spllitedpath = dirpathtoupload.Split('\\').ToArray();
        // last index must be the "base" directory on the server
        this.BaseDirectory = spllitedpath[spllitedpath.Length - 1];
    }


    public void UploadDirectory()
    {
        // rename the old folder version (if exist)
        RenameDir(BaseDirectory);
        // create a parent folder on server
        CreateDir(BaseDirectory);
        // upload the files in the most external directory of the path
        UploadAllFolderFiles(DirPathToUpload, BaseDirectory);
        // loop trough all files in subdirectories



        foreach (string dirPath in Directory.GetDirectories(DirPathToUpload, "*",
        SearchOption.AllDirectories))
        {
            // create the folder
            CreateDir(dirPath.Substring(dirPath.IndexOf(BaseDirectory), dirPath.Length - dirPath.IndexOf(BaseDirectory)));

            Console.WriteLine(dirPath.Substring(dirPath.IndexOf(BaseDirectory), dirPath.Length - dirPath.IndexOf(BaseDirectory)));
            UploadAllFolderFiles(dirPath, dirPath.Substring(dirPath.IndexOf(BaseDirectory), dirPath.Length - dirPath.IndexOf(BaseDirectory))
        }
    }

    private void UploadAllFolderFiles(string localpath, string remotepath)
    {
        string[] files = Directory.GetFiles(localpath);
        // get only the filenames and concat to remote path
        foreach (string file in files)
        {
            // full remote path
            var fullremotepath = remotepath + "\\" + Path.GetFileName(file);
            // local path
            var fulllocalpath = Path.GetFullPath(file);
            // upload to server
            Upload(fulllocalpath, fullremotepath);
        }

    }

    public bool CreateDir(string dirname)
    {
        try
        {
            WebRequest request = WebRequest.Create("ftp://" + FtpServerUrl + "/" + dirname);
            request.Method = WebRequestMethods.Ftp.MakeDirectory;
            request.Proxy = new WebProxy();
            request.Credentials = new NetworkCredential(FtpUser, FtpPass);
            using (var resp = (FtpWebResponse)request.GetResponse())
            {
                if (resp.StatusCode == FtpStatusCode.PathnameCreated)
                {
                    return true;
                }
                else
                {
                    return false;
                }
            }
        }

        catch
        {
            return false;
        }
    }

    public void Upload(string filepath, string targetpath)
    {

        using (WebClient client = new WebClient())
        {
            client.Credentials = new NetworkCredential(FtpUser, FtpPass);
            client.Proxy = null;
            var fixedpath = targetpath.Replace(@"\", "/");
            client.UploadFile("ftp://" + FtpServerUrl + "/" + fixedpath, WebRequestMethods.Ftp.UploadFile, filepath);
        }
    }

    public bool RenameDir(string dirname)
    {
        var path = "ftp://" + FtpServerUrl + "/" + dirname;
        string serverUri = path;

        try
        {
            FtpWebRequest request = (FtpWebRequest)WebRequest.Create(serverUri);
            request.Method = WebRequestMethods.Ftp.Rename;
            request.Proxy = null;
            request.Credentials = new NetworkCredential(FtpUser, FtpPass);
            // change the name of the old folder the old folder
            request.RenameTo = DateTime.Now.ToString("yyyyMMddHHmmss"); 
            FtpWebResponse response = (FtpWebResponse)request.GetResponse();

            using (var resp = (FtpWebResponse)request.GetResponse())
            {
                if (resp.StatusCode == FtpStatusCode.FileActionOK)
                {
                    return true;
                }
                else
                {
                    return false;
                }
            }
        }
        catch
        {
            return false;
        }
    }
}

创建该类的实例:

static void Main(string[] args)
{
    MyFtpClientftp = new MyFtpClient(ftpuser, ftppass, ftpServerUrl, @"C:\Users\xxxxxxxxxxx");
    ftp.UploadDirectory();
    Console.WriteLine("DONE");
    Console.ReadLine();
}

答案 3 :(得分:0)

除非您为了娱乐或自我​​改进而这样做,否则请使用商业模块。我可以从Chilkat推荐一个,但我确定还有其他人。

注意:我很确定这会解决上述问题,我要做的是在C#(C Sharp)中使用FTP上传网站。