使用C#上传文件到FTP

我尝试使用C#将file upload到FTP服务器。 该file upload,但零字节。

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 !"); } } 

现有的答案是有效的,但为什么WebClient已经实现了FTP上传整洁的WebRequesttypes的重新发明和打扰:

 using (WebClient client = new WebClient()) { client.Credentials = new NetworkCredential(ftpUsername, ftpPassword); client.UploadFile("ftp://ftpserver.com/target.zip", "STOR", localFilePath); } 
 public void UploadFtpFile(string folderName, string fileName) { FtpWebRequest request; try { string folderName; string fileName; string absoluteFileName = Path.GetFileName(fileName); request = WebRequest.Create(new Uri(string.Format(@"ftp://{0}/{1}/{2}", "127.0.0.1", folderName, absoluteFileName))) as FtpWebRequest; request.Method = WebRequestMethods.Ftp.UploadFile; request.UseBinary = 1; request.UsePassive = 1; request.KeepAlive = 1; request.Credentials = new NetworkCredential(user, pass); request.ConnectionGroupName = "group"; using (FileStream fs = File.OpenRead(fileName)) { byte[] buffer = new byte[fs.Length]; fs.Read(buffer, 0, buffer.Length); fs.Close(); Stream requestStream = request.GetRequestStream(); requestStream.Write(buffer, 0, buffer.Length); requestStream.Flush(); requestStream.Close(); } } catch (Exception ex) { } } 

如何使用

 UploadFtpFile("testFolder", "E:\\filesToUpload\\test.img"); 

在你的foreach中使用这个

你只需要一次创build文件夹

创build一个文件夹

 request = WebRequest.Create(new Uri(string.Format(@"ftp://{0}/{1}/", "127.0.0.1", "testFolder"))) as FtpWebRequest; request.Method = WebRequestMethods.Ftp.MakeDirectory; FtpWebResponse ftpResponse = (FtpWebResponse)request.GetResponse(); 

以下为我工作:

 public virtual void Send(string fileName, byte[] file) { ByteArrayToFile(fileName, file); var request = (FtpWebRequest) WebRequest.Create(new Uri(ServerUrl + fileName)); request.Method = WebRequestMethods.Ftp.UploadFile; request.UsePassive = false; request.Credentials = new NetworkCredential(UserName, Password); request.ContentLength = file.Length; var requestStream = request.GetRequestStream(); requestStream.Write(file, 0, file.Length); requestStream.Close(); var response = (FtpWebResponse) request.GetResponse(); if (response != null) response.Close(); } 

你不能读取代码中的文件参数,因为它只是文件名。

使用以下内容:

 byte[] bytes = File.ReadAllBytes(dir + file); 

要获取文件,可以将其传递给Send方法。

 public static void UploadFileToFtp(string url, string filePath, string username, string password) { var fileName = Path.GetFileName(filePath); var request = (FtpWebRequest)WebRequest.Create(url + fileName); request.Method = WebRequestMethods.Ftp.UploadFile; request.Credentials = new NetworkCredential(username, password); request.UsePassive = true; request.UseBinary = true; request.KeepAlive = false; using (var fileStream = File.OpenRead(filePath)) { using (var requestStream = request.GetRequestStream()) { fileStream.CopyTo(requestStream); requestStream.Close(); } } var response = (FtpWebResponse)request.GetResponse(); Console.WriteLine("Upload done: {0}", response.StatusDescription); response.Close(); } 

在这里find它: http : //www.snippetsource.net/Snippet/127/upload-a-file-with-ftp-in-c

在第一个例子中,必须将其更改为:

 requestStream.Flush(); requestStream.Close(); 

首先冲洗,然后closures。

这适用于我,这种方法将SFTP文件到networking中的位置。 它使用SSH.NET.2013.4.7库。一个可以免费下载。

  //Secure FTP public void SecureFTPUploadFile(string destinationHost,int port,string username,string password,string source,string destination) { ConnectionInfo ConnNfo = new ConnectionInfo(destinationHost, port, username, new PasswordAuthenticationMethod(username, password)); var temp = destination.Split('/'); string destinationFileName = temp[temp.Count() - 1]; string parentDirectory = destination.Remove(destination.Length - (destinationFileName.Length + 1), destinationFileName.Length + 1); using (var sshclient = new SshClient(ConnNfo)) { sshclient.Connect(); using (var cmd = sshclient.CreateCommand("mkdir -p " + parentDirectory + " && chmod +rw " + parentDirectory)) { cmd.Execute(); } sshclient.Disconnect(); } using (var sftp = new SftpClient(ConnNfo)) { sftp.Connect(); sftp.ChangeDirectory(parentDirectory); using (var uplfileStream = System.IO.File.OpenRead(source)) { sftp.UploadFile(uplfileStream, destinationFileName, true); } sftp.Disconnect(); } } 

使用.NET框架将file upload到FTP服务器的最简单的方法是使用WebClient.UploadFile方法 :

 WebClient client = new WebClient(); client.Credentials = new NetworkCredential("username", "password"); client.UploadFile("ftp://ftp.example.com/remote/path/file.zip", @"C:\local\path\file.zip"); 

如果你需要更好的控制, WebClient不提供(如TLS / SSLencryption等),使用FtpWebRequest 。 简单的方法是使用Stream.CopyToFileStream复制到FTPstream:

 FtpWebRequest request = (FtpWebRequest)WebRequest.Create("ftp://ftp.example.com/remote/path/file.zip"); request.Credentials = new NetworkCredential("username", "password"); request.Method = WebRequestMethods.Ftp.UploadFile; using (Stream fileStream = File.OpenRead(@"C:\local\path\file.zip")) using (Stream ftpStream = request.GetRequestStream()) { fileStream.CopyTo(ftpStream); } 

如果您需要监控上传进度,则必须自行将文件复制到内容中:

 FtpWebRequest request = (FtpWebRequest)WebRequest.Create("ftp://ftp.example.com/remote/path/file.zip"); request.Credentials = new NetworkCredential("username", "password"); request.Method = WebRequestMethods.Ftp.UploadFile; using (Stream fileStream = File.OpenRead(@"C:\local\path\file.zip")) using (Stream ftpStream = request.GetRequestStream()) { byte[] buffer = new byte[10240]; int read; while ((read = fileStream.Read(buffer, 0, buffer.Length)) > 0) { ftpStream.Write(buffer, 0, read); Console.WriteLine("Uploaded {0} bytes", fileStream.Position); } } 

对于GUI进度(WinForms ProgressBar ),请参阅C#示例:
我们如何显示进度条上传与FtpWebRequest

如果您想上传文件夹中的所有文件,请参阅
使用WebClient上传文件的目录 。

我观察到 –

  1. FtpwebRequest丢失。
  2. 由于目标是FTP,所以需要NetworkCredential。

我准备了一个像这样工作的方法,可以用参数TargetDestinationPathreplacevariablesftpurl的值。 我在WinForms应用程序上testing了这个方法:

 private void UploadProfileImage(string TargetFileName, string TargetDestinationPath, string FiletoUpload) { //Get the Image Destination path string imageName = TargetFileName; //you can comment this string imgPath = TargetDestinationPath; string ftpurl = "ftp://downloads.abc.com/downloads.abc.com/MobileApps/SystemImages/ProfileImages/" + imgPath; string ftpusername = krayknot_DAL.clsGlobal.FTPUsername; string ftppassword = krayknot_DAL.clsGlobal.FTPPassword; string fileurl = FiletoUpload; FtpWebRequest ftpClient = (FtpWebRequest)FtpWebRequest.Create(ftpurl); ftpClient.Credentials = new System.Net.NetworkCredential(ftpusername, ftppassword); ftpClient.Method = System.Net.WebRequestMethods.Ftp.UploadFile; ftpClient.UseBinary = true; ftpClient.KeepAlive = true; System.IO.FileInfo fi = new System.IO.FileInfo(fileurl); ftpClient.ContentLength = fi.Length; byte[] buffer = new byte[4097]; int bytes = 0; int total_bytes = (int)fi.Length; System.IO.FileStream fs = fi.OpenRead(); System.IO.Stream rs = ftpClient.GetRequestStream(); while (total_bytes > 0) { bytes = fs.Read(buffer, 0, buffer.Length); rs.Write(buffer, 0, bytes); total_bytes = total_bytes - bytes; } //fs.Flush(); fs.Close(); rs.Close(); FtpWebResponse uploadResponse = (FtpWebResponse)ftpClient.GetResponse(); string value = uploadResponse.StatusDescription; uploadResponse.Close(); } 

如有任何问题,请告知我,或者这里有一个链接可以帮助您:

https://msdn.microsoft.com/en-us/library/ms229715(v=vs.110).aspx