我尝试使用C#将文件上传到FTP服务器。文件已上传,但字节为零。
private void button2_Click(object sender, EventArgs e) { var dirPath = @"C:/Documents and Settings/sander.GD/Bureaublad/test/"; ftp ftpClient = new ftp("ftp://example.com/", "username", "password"); string[] files = Directory.GetFiles(dirPath,"*.*"); var uploadPath = "/httpdocs/album"; foreach (string file in files) { ftpClient.createDirectory("/test"); ftpClient.upload(uploadPath + "/" + Path.GetFileName(file), file); } if (string.IsNullOrEmpty(txtnaam.Text)) { MessageBox.Show("Gelieve uw naam in te geven !"); } }
现有的答案是有效的,但是为什么要重新发明轮子并打扰较低级别的WebRequest类型,而又WebClient已经巧妙地实现了FTP上传:
WebRequest
WebClient
using (var client = new WebClient()) { client.Credentials = new NetworkCredential(ftpUsername, ftpPassword); client.UploadFile("ftp://host/path.zip", WebRequestMethods.Ftp.UploadFile, localFile); }