从 ftp 服务器下载之前检测文件大小? C#错误

File size detection before downloading from an ftp server? C# error

我有一个 C# 作业,创建一个下载管理器以从 ftp 服务器下载文件,条件如下:

  1. Selection of an audio file on a server.
  2. Detection of file size.
  3. Asynchronous transmission of the file to your work PC via ftp.
  4. Representation of the progress of the download.

其实三个我都完成了,几乎全部完成了,除了第二个条件在下载前获取文件大小时出现了一些错误,我的程序崩溃了,出现了这样的错误:

Error

这是我的下载器的代码:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Net;

namespace DownloadDataFTP
{
    public partial class ftpForm : Form
    {
        public ftpForm()
        {
            InitializeComponent();
        }

    private byte[] downloadedData;

    //Connects to the FTP server and downloads the file
    private void downloadFile(string FTPAddress, string filename, string username, string password)
    {
        downloadedData = new byte[0];

        try
        {
            //Create FTP request
            //Note: format is ftp://server.com/file.ext
            FtpWebRequest request = FtpWebRequest.Create(FTPAddress + "/" + filename) as FtpWebRequest;


            //Get the file size first (for progress bar)
            request.Method = WebRequestMethods.Ftp.GetFileSize;
            request.Credentials = new NetworkCredential(username, password);
            request.UsePassive = true;
            request.UseBinary = true;
            request.KeepAlive = true; //don't close the connection

            int dataLength = (int)request.GetResponse().ContentLength;


            //Now get the actual data
            request = FtpWebRequest.Create(FTPAddress + "/" + filename) as FtpWebRequest;

            request.Method = WebRequestMethods.Ftp.DownloadFile;
            request.Credentials = new NetworkCredential(username, password);
            request.UsePassive = true;
            request.UseBinary = true;
            request.KeepAlive = false; //close the connection when done

            //Set up progress bar
            progressBar1.Value = 0;
            progressBar1.Maximum = dataLength;
            lbProgress.Text = "0/" + dataLength.ToString();

            //Streams
            FtpWebResponse response = request.GetResponse() as FtpWebResponse;
            Stream reader = response.GetResponseStream();

            //Download to memory
            //Note: adjust the streams here to download directly to the hard drive
            MemoryStream memStream = new MemoryStream();
            byte[] buffer = new byte[1024]; //downloads in chuncks

            while (true)
            {
                Application.DoEvents(); //prevent application from crashing

                //Try to read the data
                int bytesRead = reader.Read(buffer, 0, buffer.Length);

                if (bytesRead == 0)
                {
                    //Nothing was read, finished downloading
                    progressBar1.Value = progressBar1.Maximum;
                    lbProgress.Text = dataLength.ToString() + "/" + dataLength.ToString();

                    Application.DoEvents();
                    break;
                }
                else
                {
                    //Write the downloaded data
                    memStream.Write(buffer, 0, bytesRead);

                    //Update the progress bar
                    if (progressBar1.Value + bytesRead <= progressBar1.Maximum)
                    {
                        progressBar1.Value += bytesRead;
                        lbProgress.Text = progressBar1.Value.ToString() + "/" + dataLength.ToString();

                        progressBar1.Refresh();
                        Application.DoEvents();
                    }
                }
            }

            //Convert the downloaded stream to a byte array
            downloadedData = memStream.ToArray();

            //Clean up
            reader.Close();
            memStream.Close();
            response.Close();

            MessageBox.Show("Downloaded Successfully");
        }
        catch (Exception)
        {
            MessageBox.Show("There was an error connecting to the FTP Server.");
        }

        txtData.Text = downloadedData.Length.ToString();
        this.Text = "Download and Upload Data through FTP";

        username = string.Empty;
        password = string.Empty;
    }

    //Upload file via FTP
    private void Upload(string FTPAddress, string filePath, string username, string password)
    {
        //Create FTP request
        FtpWebRequest request = (FtpWebRequest)FtpWebRequest.Create(FTPAddress + "/" + Path.GetFileName(filePath));

        request.Method = WebRequestMethods.Ftp.UploadFile;
        request.Credentials = new NetworkCredential(username, password);
        request.UsePassive = true;
        request.UseBinary = true;
        request.KeepAlive = false;

        //Load the file
        FileStream stream = File.OpenRead(filePath);
        byte[] buffer = new byte[stream.Length];

        stream.Read(buffer, 0, buffer.Length);
        stream.Close();

        //Upload file
        Stream reqStream = request.GetRequestStream();
        reqStream.Write(buffer, 0, buffer.Length);
        reqStream.Close();

        MessageBox.Show("Uploaded Successfully");
    }

    //get file size for downloading
    private void FileSize_down(string FTPAddress, string filename)
    {
        FtpWebRequest request = FtpWebRequest.Create(FTPAddress + "/" + filename) as FtpWebRequest;
        request.Method = WebRequestMethods.Ftp.GetFileSize;


        long dataLength = (long)request.GetResponse().ContentLength;
        sizeFile.Text = dataLength.ToString();
    }

    //get file size for uploading
    private void FileSize_up(string filename)
    {
        if (UpFile.Text != "")
        {
            //direction file
            FileInfo f = new FileInfo(UpFile.Text);
            //add size to text box
            textBox1.Text = f.Length.ToString();
        }
        else
            MessageBox.Show("Choose file to upload");
    }

    //Connects to the FTP server and request the list of available files
    private void getFileList(string FTPAddress, string username, string password)
    {
        List<string> files = new List<string>();

        try
        {
            //Create FTP request
            FtpWebRequest request = FtpWebRequest.Create(FTPAddress) as FtpWebRequest;

            request.Method = WebRequestMethods.Ftp.ListDirectory;
            request.Credentials = new NetworkCredential(username, password);
            request.UsePassive = true;
            request.UseBinary = true;
            request.KeepAlive = false;


            FtpWebResponse response = request.GetResponse() as FtpWebResponse;
            Stream responseStream = response.GetResponseStream();
            StreamReader reader = new StreamReader(responseStream);

            while (!reader.EndOfStream)
            {
                Application.DoEvents();
                files.Add(reader.ReadLine());
            }

            //Clean-up
            reader.Close();
            responseStream.Close(); //redundant
            response.Close();
        }
        catch (Exception)
        {
            MessageBox.Show("There was an error connecting to the FTP Server");
        }

        username = string.Empty;
        password = string.Empty;

        this.Text = "Download and Upload Data through FTP"; //Back to normal title

        //If the list was successfully received, display it to the user
        //through a dialog
        if (files.Count != 0)
        {
            listDialogForm dialog = new listDialogForm(files);
            if (dialog.ShowDialog() == DialogResult.OK)
            {
                //Update the File Name field
                txtFileName.Text = dialog.ChosenFile;
            }
        }
    }

    //Make sure the FTP server address has ftp:// at the beginning
    private void txtFTPAddress_Leave(object sender, EventArgs e)
    {
        if (!txtFTPAddress.Text.StartsWith("ftp://"))
            txtFTPAddress.Text = "ftp://" + txtFTPAddress.Text;
    }

这是获取下载文件大小的部分。

    //get file size for downloading
    private void FileSize_down(string FTPAddress, string filename)
    {
        FtpWebRequest request = FtpWebRequest.Create(FTPAddress + "/" + filename) as FtpWebRequest;
        request.Method = WebRequestMethods.Ftp.GetFileSize;


        long dataLength = (long)request.GetResponse().ContentLength;
        sizeFile.Text = dataLength.ToString();
    }

非常感谢!

您收到 530(未登录)错误。似乎这就是问题所在。在您的其他方法(downloadFile、getFileList 等)中,您包括:

    request.Credentials = new NetworkCredential(username, password);
    request.UsePassive = true;
    request.UseBinary = true;
    request.KeepAlive = false;

在你的 Filesize_down 你没有。