如何在 c# windows 应用程序中上传多个文件

how to upload multiple files in c# windows application

我想使用一个上传按钮上传多个文件。当我 select 多个文件时,它会上传并保留其余文件。这是我的代码:

private void buttonBrowse_Click(object sender, EventArgs e)
{
    try
    {
        var o = new OpenFileDialog();
        o.Multiselect = true;
        if (o.ShowDialog() == System.Windows.Forms.DialogResult.OK)
        {
            string FileName = o.FileName;
            string filenames = Path.GetFileName(o.FileName);
            FileName = FileName.Replace(filenames,"").ToString();
            FTPUtility obj = new FTPUtility();
            if (obj.UploadDocsToFTP(FileName, filenames))
            {
                MessageBox.Show("File Uploaded Successfully...", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                loadfiles();
            }
        }

        else
        {
            MessageBox.Show("File Not Uploaded", "Error Message", MessageBoxButtons.OK, MessageBoxIcon.Error);
        }
        this.LoadFiles();
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.Message);
    }
}

OpenFileDialogMultiSelect 属性 设置为 true 然后使用 FileNames 属性 获取所有选定的文件。

o.FileNames.ToList().ForEach(file =>
 {
     //upoaad each file separately
 });

FileNames
Gets the file names of all selected files in the dialog box.

例如你的代码可能是这样的:

var o = new OpenFileDialog();
o.Multiselect = true;

if (o.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
    var ftp = new FTPUtility();
    var failedToUploads= new List<string>();
    var uploads= new List<string>();

    o.FileNames.ToList().ForEach(file =>
    {
        var upload= ftp.UploadDocsToFTP(file, Path.GetFileName(file)));
        if(upload)
            uploads.Add(file);
        else 
            failedToUploads.Add(file);
    });
    var message= string.Format("Files Uploaded: \n {0}", string.Join("\n", uploads.ToArray()));
    if(failedToUploads.Count>0)
        message += string.Format("\nFailed to Upload: \n {0}", string.Join("\n", failedToUploads.ToArray()));

    MessageBox.Show(message);
    this.LoadFiles();
}

通过这种方式,您可以显示一条消息,通知用户有关他上传的文件或其中一个文件上传失败。