Dosyayı C # kullanarak FTP'ye yükleyin


112

C # ile bir FTP sunucusuna dosya yüklemeyi deniyorum. Dosya yüklendi ancak sıfır bayt ile.

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

18
Neden neredeyse 2 yıl sonra orijinal FTP kimlik bilgileri hala çalışıyor?
— FreeAsInBeer


@Frederic ile bağlantılı soruda anlatılanları deneyebilir misiniz ve geri dönebilir misiniz ...
— dahası

Yanıtlar:


273

Mevcut yanıtlar geçerlidir, ancak neden tekerleği yeniden icat edin ve FTP yüklemesini düzgün bir şekilde uygularken daha düşük seviyeli WebRequesttürlerle WebClientuğraşın:

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

39
Sadece bir kuruş: WebRequestMethods.Ftp.UploadFile için sihirli "STOR" dizesini değiştirebilirsiniz
— Tamam'ı tıklayın

Ne yazık ki, bir dosya yüklemek için WebClient'i yeni bir dizin oluşturmak için kullanmanın bir yolu yok gibi görünüyor.
— danludwig

1
PSA: webrequest artık tavsiye edilmiyor, bu artık resmi alternatifler
— Pacharrin

Merhaba UploadFile yöntemindeki path.zip neyi gösterir? Ana bilgisayar adından sonra eklemek için bir dosya adına ihtiyacım var mı? Göndereceğim bir txt dosyam var, dosya adı ve o dosyanın yolunun localFile'da belirtildiğini düşündüm.
— Skanda

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

Nasıl kullanılır

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

bunu foreach'ınızda kullanın

ve yalnızca bir kez klasör oluşturmanız gerekir

bir klasör oluşturmak için

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
Cevap, bir aramayı kaçırır request.GetResponse(). Bu olmadan yükleme bazı sunucularda (haklı olarak) çalışmaz. Nasıl yapılır: FTP ile Dosya Yükleme konusuna bakın .
— Martin Prikryl

İstisnaları sessizce yutmak için -1'i tercih ediyorum. Lütfen o zararlı deneme-yakalama engelini kaldırır mısınız?
— Heinzi

33

En kolay yol

.NET çerçevesini kullanarak bir FTP sunucusuna dosya yüklemenin en önemsiz yolu şu WebClient.UploadFileyöntemi kullanmaktır :

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

Gelişmiş seçenekler

Daha büyük bir kontrole ihtiyacınız varsa WebClient( TLS / SSL şifreleme , ASCII modu, aktif mod vb FtpWebRequest. Gibi), kullanın . Kolay yol, aşağıdakileri FileStreamkullanarak bir FTP akışına kopyalamaktır Stream.CopyTo:

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

İlerleme izleme

Bir yükleme ilerlemesini izlemeniz gerekiyorsa, içeriği parçalara göre kopyalamanız gerekir:

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 ilerlemesi (WinForms ProgressBar) için, C # örneğine bakın:
FtpWebRequest ile karşıya yükleme için ilerleme çubuğunu nasıl gösterebiliriz


Klasör yükleniyor

Bir klasördeki tüm dosyaları yüklemek istiyorsanız,
WebClient kullanarak dosyaların dizinini FTP sunucusuna yükleme konusuna bakın .

Özyinelemeli yükleme için, bkz
. C # 'da FTP sunucusuna yinelemeli yükleme


10

Aşağıdakiler benim için çalışıyor:

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

Sadece dosya adı olduğu için kodunuzdaki dosya parametresini okuyamazsınız.

Aşağıdakileri kullanın:

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

Dosyayı almak için Sendyönteme iletebilirsiniz .


merhaba, içinde dosyalar olan bir klasörüm var .. bunu bir FTP sunucusuna nasıl yükleyebilirim? Bu kodun nasıl çalıştığını tam olarak bilmiyorum?
— webvision

foreach döngüsünde bu yöntemi uygun girdiyle çağırın.
— 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 neden ayarladınız? RequestStream.Close () işleminin gerekli olduğundan emin misiniz? İçinde requestStream kullanıyorsunuz, bu yüzden akışı kendi kendine kapatacağını düşünüyorum.
— Kate

2

İlk örnekte bunları şu şekilde değiştirmelisiniz:

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

İlk yıkama ve kapanıştan sonra.


1

Bu benim için çalışıyor, bu yöntem bir dosyayı ağınızdaki bir konuma SFTP ile gönderecek. SSH.NET.2013.4.7 kütüphanesini kullanır, sadece ücretsiz olarak indirilebilir.

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

Bu cevap, benim sftp'm için tek çözüm gibi görünüyor. Test etmek için bekliyorum.
— Olorunfemi Ajibulu

1

yayın tarihi: 06/26/2018

https://docs.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}");
        }
    }
}
}

0

Bunu gözlemledim -

  1. FtpwebRequest eksik.
  2. Hedef FTP olduğundan, NetworkCredential gereklidir.

Bu şekilde çalışan bir yöntem hazırladım, ftpurl değişkeninin değerini TargetDestinationPath parametresi ile değiştirebilirsiniz. Bu yöntemi winforms uygulamasında test ettim:

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

Herhangi bir sorun olması durumunda bana bildirin ya da işte size yardımcı olabilecek bir bağlantı daha:

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

Sitemizi kullandığınızda şunları okuyup anladığınızı kabul etmiş olursunuz: Çerez Politikası ve Gizlilik Politikası.
Licensed under cc by-sa 3.0 with attribution required.