使用FTP C#上传整个目录(C# Upload whole directory using FTP

2019-07-03 17:33发布

我正在试图做的是上传在C#(C夏普),使用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目录?

Answer 1:

问题解决了! :)

好了,所以我设法写方法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));
        }
    }

它工作得很好:)



Answer 2:

我写了一个FTP CLASSE,也包裹在一个WinForms用户控件。 你可以看到这篇文章在我的代码的FtpClient类和WinForm控件 。



Answer 3:

我写了一个可重用的类来整个目录上传到ftp site Windows服务器上,
该方案还重命名旧版本的文件夹(我用它在我的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();
}


Answer 4:

除非你这样做是为了好玩或自强不息,使用商业模块。 我可以推荐一个从奇尔卡特 ,但我敢肯定还有其他的。

注:我敢肯定,这也回答了上述问题, 我试图做的是上传在C#(C夏普),使用FTP网站。



文章来源: C# Upload whole directory using FTP