使用C#将文件上传到FTP

web*_*ion 105 .net c# ftp file-upload

我尝试使用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 !");
    }
}
Run Code Online (Sandbox Code Playgroud)

Sae*_*ini 254

现有的答案是有效的,但为什么重新发明轮子并打扰较低级别的WebRequest类型,同时WebClient已经巧妙地实现了FTP上传:

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

  • 只需一分钱:你可以为WebRequestMethods.Ftp.UploadFile替换魔术字符串"STOR" (38认同)
  • 的确,为什么不使用`WebClient`?人们喜欢使事情复杂化. (20认同)
  • 我需要更低级别的访问权限来更改FTP服务器上的目录.互联网上提供的其他解决方案(使用WebRequest)似乎不起作用.FTP用户有权导航到root(在FileZilla中验证),但所有上载请求最终都在主目录中,这是错误的.没有要求服务器人员将用户的主目录更改为/(在多个服务器上)我被卡住了. (3认同)
  • PSA:不再推荐 webrequest,这是现在[官方替代品](/sf/ask/96037511/) (3认同)
  • @saeb:我用这个但抛出以下错误。“远程服务器返回错误:(550)文件不可用(例如,找不到文件,无法访问)。” ,使用Filezilla上传时,其工作正常。 (2认同)

cde*_*dev 40

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();
    }
}
Run Code Online (Sandbox Code Playgroud)

如何使用

UploadFtpFile("testFolder", "E:\\filesToUpload\\test.img");
Run Code Online (Sandbox Code Playgroud)

在你的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();
Run Code Online (Sandbox Code Playgroud)

  • 答案错过了对`request.GetResponse()`的调用.没有它,上传将不会(正确地)在某些服务器上运行.请参阅[如何:使用FTP上载文件](https://msdn.microsoft.com/en-us/library/ms229715.aspx). (3认同)

Mar*_*ryl 26

最简单的方法

使用.NET框架将文件上传到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");
Run Code Online (Sandbox Code Playgroud)

高级选项

如果您需要更大的控件WebClient(如TLS/SSL加密,ASCII模式,活动模式等),请使用FtpWebRequest.简单的方法是FileStream使用Stream.CopyTo以下方法将a复制到FTP流:

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);
}
Run Code Online (Sandbox Code Playgroud)

进度监测

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

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);
    } 
}
Run Code Online (Sandbox Code Playgroud)

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


正在上传文件夹

如果要从文件夹上载所有文件,请参阅
使用WebClient上载文件目录.


Bjö*_*son 9

以下适用于我:

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();
}
Run Code Online (Sandbox Code Playgroud)

您无法读取代码中的file参数,因为它只是文件名.

使用以下内容:

byte[] bytes = File.ReadAllBytes(dir + file);
Run Code Online (Sandbox Code Playgroud)

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


小智 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();
}
Run Code Online (Sandbox Code Playgroud)

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