簡體   English   中英

如何將多個文件上傳到我的FTP站點?

[英]How can I upload more than one file to my FTP site?

這個想法是,如果我選擇了多個文件,則在上載時上傳一個文件,然后在上載完成后再上傳下一個,依此類推。

我將filedialoug更改為可以選擇多個:

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

我可以選擇多個文件,問題是當使用斷點時,我在this.txtUploadFile.Text上看到的文件只有我選擇的第一個文件。 txtUploadFile是一個textBox。

第一件事是:如何在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";
    }
}

我也有一個帶有progressBar的backgroundworker,所以正在上傳progressBar的每個文件都應該顯示今天的上傳進度,因為一個文件只能顯示一個文件,因為我只能上傳一個文件:

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

它有點長,但是由於它們都相互連接,我找不到縮小代碼的方法。

我需要做的是,如果我選擇了多個文件,則創建一個隊列,並在完成下一個文件的上傳后自動上載一個文件,依此類推,直到最后一個文件。

今天,我只能上傳一個文件。 每次單個文件。 我需要它會自動上傳所有選定的文件。 現在使用progressBar和backgroundworker。

以下是從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

並迭代這些元素以將其一一上傳。

FileNames屬性

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM