如何将多个文件上传到我的 FTP 站点

本文关键字:我的 FTP 站点 文件 | 更新日期: 2023-09-27 18:32:22

这个想法是,如果我选择了多个文件,然后在上传时上传一个文件,然后在上传完成后上传下一个文件,依此类推。

我更改了文件拨号以便能够选择多个:

private void btnBrowse_Click(object sender, EventArgs e)
{
    openFileDialog1.Multiselect = true;
    if (this.openFileDialog1.ShowDialog() != DialogResult.Cancel)
        this.txtUploadFile.Text = this.openFileDialog1.FileName;
}

可以选择多个文件,问题是当使用断点时,我在这个.txtUploadFile.text上看到一个文件,只有我选择的第一个文件。 txtUploadFile 是一个文本框。

第一件事是:如何在textBox(txtUploadFile)上看到所有选定的文件,而不仅仅是一个?或者我怎样才能得到一些指示,表明我选择的所有文件都确实选择了?也许在文本框中以某种方式显示所有文件都选择了的内容?

重要的部分是:如何一一上传所有选定的文件?

这是启动文件上传的按钮单击事件:

private void btnUpload_Click(object sender, EventArgs e)
{
    if(this.ftpProgress1.IsBusy)
    {
        this.ftpProgress1.CancelAsync();
        this.btnUpload.Text = "Upload";
    }
    else
    {
        FtpSettings f = new FtpSettings();
        f.Host = this.txtHost.Text;
        f.Username = this.txtUsername.Text;
        f.Password = this.txtPassword.Text;
        f.TargetFolder = this.txtDir.Text;
        f.SourceFile = this.txtUploadFile.Text;
        f.Passive = this.chkPassive.Checked;
        try
        {
            f.Port = Int32.Parse(this.txtPort.Text);
        }
        catch { }
        this.toolStripProgressBar1.Visible = true;
        this.ftpProgress1.RunWorkerAsync(f);
        this.btnUpload.Text = "Cancel";
    }
}

我还有一个带有进度条的后台工作者,因此每个上传进度条的文件都应该显示今天为一个文件显示的上传进度,因为我只能上传一个文件:

private void ftpProgress1_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
    this.toolStripStatusLabel1.Text = e.UserState.ToString();    // The message will be something like: 45 Kb / 102.12 Mb
    this.toolStripProgressBar1.Value = Math.Min(this.toolStripProgressBar1.Maximum, e.ProgressPercentage);
}
private void ftpProgress1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
    if(e.Error != null)
        MessageBox.Show(e.Error.ToString(), "FTP error");
    else if(e.Cancelled)
        this.toolStripStatusLabel1.Text = "Upload Cancelled";
    else
        this.toolStripStatusLabel1.Text = "Upload Complete";
    this.btnUpload.Text = "Upload";
    this.toolStripProgressBar1.Visible = true;
}

最后是FTP上传器的类:

using System;
using System.ComponentModel;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Net;
using System.Text;
namespace FTP_ProgressBar
{
    public partial class FtpProgress : BackgroundWorker
    {
        public static string ConnectionError;
        private FtpSettings f;
        public FtpProgress()
        {
            InitializeComponent();
        }
        public FtpProgress(IContainer container)
        {
            container.Add(this);
            InitializeComponent();
        }
        private void FtpProgress_DoWork(object sender, DoWorkEventArgs e)
        {
            try
            {
                BackgroundWorker bw = sender as BackgroundWorker;
                f = e.Argument as FtpSettings;
                string UploadPath = String.Format("{0}/{1}{2}", f.Host, f.TargetFolder == "" ? "" : f.TargetFolder + "/", Path.GetFileName(f.SourceFile));
                if (!UploadPath.ToLower().StartsWith("ftp://"))
                    UploadPath = "ftp://" + UploadPath;
                FtpWebRequest request = (FtpWebRequest)WebRequest.Create(UploadPath);
                request.UseBinary = true;
                request.UsePassive = f.Passive;
                request.Method = WebRequestMethods.Ftp.UploadFile;
                request.Timeout = 300000;
                request.Credentials = new NetworkCredential(f.Username, f.Password);
                long FileSize = new FileInfo(f.SourceFile).Length;
                string FileSizeDescription = GetFileSize(FileSize);
                int ChunkSize = 4096, NumRetries = 0, MaxRetries = 50;
                long SentBytes = 0;
                byte[] Buffer = new byte[ChunkSize];
                using (Stream requestStream = request.GetRequestStream())
                {
                    using (FileStream fs = File.Open(f.SourceFile, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
                    {
                        int BytesRead = fs.Read(Buffer, 0, ChunkSize);
                        while (BytesRead > 0)
                        {
                            try
                            {
                                if (bw.CancellationPending)
                                    return;
                                requestStream.Write(Buffer, 0, BytesRead);
                                SentBytes += BytesRead;
                                string SummaryText = String.Format("Transferred {0} / {1}", GetFileSize(SentBytes), FileSizeDescription);
                                bw.ReportProgress((int)(((decimal)SentBytes / (decimal)FileSize) * 100), SummaryText);
                            }
                            catch (Exception ex)
                            {
                                Debug.WriteLine("Exception: " + ex.ToString());
                                if (NumRetries++ < MaxRetries)
                                {
                                    fs.Position -= BytesRead;
                                }
                                else
                                {
                                    throw new Exception(String.Format("Error occurred during upload, too many retries. 'n{0}", ex.ToString()));
                                }
                            }
                            BytesRead = fs.Read(Buffer, 0, ChunkSize);
                        }
                    }
                }
                using (FtpWebResponse response = (FtpWebResponse)request.GetResponse())
                    System.Diagnostics.Debug.WriteLine(String.Format("Upload File Complete, status {0}", response.StatusDescription));
            }
            catch (WebException ex)
            {
                switch (ex.Status)
                {
                    case WebExceptionStatus.NameResolutionFailure:
                        ConnectionError = "Error: Please check the ftp address";
                        break;
                    case WebExceptionStatus.Timeout:
                        ConnectionError = "Error: Timout Request";
                        break;
                }
            }
        }
        public static string GetFileSize(long numBytes)
        {
            string fileSize = "";
            if(numBytes > 1073741824)
                fileSize = String.Format("{0:0.00} Gb", (double)numBytes / 1073741824);
            else if(numBytes > 1048576)
                fileSize = String.Format("{0:0.00} Mb", (double)numBytes / 1048576);
            else
                fileSize = String.Format("{0:0} Kb", (double)numBytes / 1024);
            if(fileSize == "0 Kb")
                fileSize = "1 Kb";
            return fileSize;
        }
    }
    public class FtpSettings
    {
        public string Host, Username, Password, TargetFolder, SourceFile;
        public bool Passive;
        public int Port = 21;
    }
}

它有点长,但我找不到缩小代码范围的方法,因为它都是相互连接的。

我需要做的是,如果我选择了多个文件,则创建类似队列的内容,并在完成上传后自动上传一个文件,依此类推,直到最后一个文件。

今天我只能上传一个文件。每次单个文件。我需要它会自动上传所有选定的文件。像现在一样使用进度条和后台工作者。

如何将多个文件上传到我的 FTP 站点

以下是如何从 ftp - ftp 服务器的地址的目录中上传多个文件的过程:

    private void uploadFTP(DirectoryInfo d, string ftp)
    {
        FileInfo[] flist = d.GetFiles();
        if (flist.GetLength(0) > 0)
        {
            foreach (FileInfo txf in flist)
            {
                FtpWebRequest request = (FtpWebRequest)FtpWebRequest.Create(ftp + txf.Name);
                request.Method = WebRequestMethods.Ftp.UploadFile;
                request.Credentials = new NetworkCredential("username", "password");
                request.UsePassive = true;
                request.UseBinary = true;
                request.KeepAlive = false;
                FileStream stream = File.OpenRead(txf.FullName);
                byte[] buffer = new byte[stream.Length];
                stream.Read(buffer, 0, buffer.Length);
                stream.Close();
                Stream reqStream = request.GetRequestStream();
                reqStream.Write(buffer, 0, buffer.Length);
                reqStream.Close();
                txf.Delete();
            }
        }
    }

你应该使用

OpenFileDialog1.FileNames

并迭代这些元素以逐个上传它们。

文件名属性