使用C#上传文件到FTP

138
我尝试使用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 !");
    }
}

1
可能是上传文件到FTP的重复问题。 - Frédéric
10个回答

304

现有的答案是有效的,但为什么要重新发明轮子并烦恼于低级别的WebRequest类型,而WebClient已经很好地实现了FTP上传:

using (var client = new WebClient())
{
    client.Credentials = new NetworkCredential(ftpUsername, ftpPassword);
    client.UploadFile("ftp://host/path.zip", WebRequestMethods.Ftp.UploadFile, localFile);
}

4
PSA: webrequest不再被推荐使用,现在有官方替代方案 - Pacharrin

57

最简单的方法

使用 .NET Framework 将文件上传到 FTP 服务器最简单的方式是使用 WebClient.UploadFile 方法

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

高级选项

如果你需要更多的控制权,而WebClient没有提供(例如 TLS/SSL 加密,ascii/text 传输模式,主动模式,传输恢复,进度监测等),请使用FtpWebRequest。最简单的方法是使用Stream.CopyToFileStream复制到FTP流中:

var url = "ftp://ftp.example.com/remote/path/file.zip";
FtpWebRequest request = (FtpWebRequest)WebRequest.Create(url);
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);
}

进度监控

如果您需要监控上传的进度,您必须自己逐块复制内容:

var url = "ftp://ftp.example.com/remote/path/file.zip";
FtpWebRequest request = (FtpWebRequest)WebRequest.Create(url);
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将文件夹中的文件上传到FTP服务器.

对于递归上传,请参见
C#中的递归上传到FTP服务器


50

.NET 5 指南

async Task<FtpStatusCode> FtpFileUploadAsync(string ftpUrl, string userName, string password, string filePath)
{
    FtpWebRequest request = (FtpWebRequest)WebRequest.Create(ftpUrl);
    request.Method = WebRequestMethods.Ftp.UploadFile;
    request.Credentials = new NetworkCredential(userName, password);

    using (FileStream fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read))
    using (Stream requestStream = request.GetRequestStream())
    {
        await fileStream.CopyToAsync(requestStream);
    }

    using (FtpWebResponse response = (FtpWebResponse)await request.GetResponseAsync())
    {
        return response.StatusCode;
    }
}

.NET框架

public void UploadFtpFile(string folderName, string fileName)
{

    FtpWebRequest request;

    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();
    }
}

如何使用
UploadFtpFile("testFolder", "E:\\filesToUpload\\test.img");

在您的foreach中使用此代码

您只需要创建一次文件夹

要创建一个文件夹

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();

3
这个答案缺少调用 request.GetResponse() 的代码。没有这个调用,上传在某些服务器上将无法正常工作。请参见 如何:使用 FTP 上传文件 - Martin Prikryl

10
以下对我有效:
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();
}

你不能直接读取代码中的send the file参数,因为它只是文件名。请使用以下内容:
byte[] bytes = File.ReadAllBytes(dir + file);

为了获取文件,以便将其传递给Send方法。

你好, 我有一个文件夹里面有很多文件.. 我该如何将它们上传到FTP服务器上? 这段代码我不确定它是如何工作的? - webvision
在 foreach 循环中,使用相应的输入调用此方法。 - nRk

8
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();
}

为什么要将KeepAlive设置为false?您确定需要请求requestStream.Close()吗?您在using内部使用requestStream,因此我认为它会自动关闭流。 - Kate

2
在第一个示例中,必须将这些更改为:
requestStream.Flush();
requestStream.Close();

先刷新,然后关闭。


1
发布日期:06/26/2018

https://learn.microsoft.com/en-us/dotnet/framework/network-programming/how-to-upload-files-with-ftp

using System;
using System.IO;
using System.Net;
using System.Text;

namespace Examples.System.Net
{
    public class WebRequestGetExample
    {
    public static void Main ()
    {
        // Get the object used to communicate with the server.
        FtpWebRequest request = 
(FtpWebRequest)WebRequest.Create("ftp://www.contoso.com/test.htm");
        request.Method = WebRequestMethods.Ftp.UploadFile;

        // This example assumes the FTP site uses anonymous logon.
        request.Credentials = new NetworkCredential("anonymous", 
"janeDoe@contoso.com");

        // Copy the contents of the file to the request stream.
        byte[] fileContents;
        using (StreamReader sourceStream = new StreamReader("testfile.txt"))
        {
            fileContents = Encoding.UTF8.GetBytes(sourceStream.ReadToEnd());
        }

        request.ContentLength = fileContents.Length;

        using (Stream requestStream = request.GetRequestStream())
        {
            requestStream.Write(fileContents, 0, fileContents.Length);
        }

        using (FtpWebResponse response = (FtpWebResponse)request.GetResponse())
        {
            Console.WriteLine($"Upload File Complete, status 
{response.StatusDescription}");
        }
    }
}
}

1
这对我很有效,此方法将文件通过SFTP传输到您网络中的位置。它使用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();
        }
    }

这个答案似乎是我sftp的唯一解决方案。等待测试它。 - Olorunfemi Davis
问题是关于FTP,而不是SFTPSFTP是完全不同的,不是FTP的安全版本。 - Gray Programmerz
回答了这个问题8年前,是我最初的回答之一。更像是一个例子。必须非常准确地与你们解释哈哈。你不知道我为什么给出那个答案。与FTP或SFTP无关。查看我的Stack Overflow收件箱。多年没访问该网站哈哈。 - C.Poh

1

我发现最好的方法是使用FluentFtp。您可以在此处找到存储库: https://github.com/robinrodricks/FluentFTP 以及快速入门示例: https://github.com/robinrodricks/FluentFTP/wiki/Quick-Start-Example

实际上,一些人推荐使用WebRequest类,但Microsoft不再推荐使用,请查看此页面: https://learn.microsoft.com/en-us/dotnet/api/system.net.webrequest?view=net-5.0

// create an FTP client and specify the host, username and password
// (delete the credentials to use the "anonymous" account)
FtpClient client = new FtpClient("123.123.123.123", "david", "pass123");

// connect to the server and automatically detect working FTP settings
client.AutoConnect();

// upload a file and retry 3 times before giving up
client.RetryAttempts = 3;
client.UploadFile(@"C:\MyVideo.mp4", "/htdocs/big.txt", 
    FtpRemoteExists.Overwrite, false, FtpVerify.Retry);

// disconnect! good bye!
client.Disconnect();

0

我注意到 -

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

我准备了一个方法,它的工作方式如下,您可以用参数TargetDestinationPath替换变量ftpurl的值。我在winforms应用程序上测试过这个方法:

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


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接