如何在c#windows应用程序上传多个文件 [英] how to upload multiple files in c# windows application

查看:176
本文介绍了如何在c#windows应用程序上传多个文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I want to upload multiple files using single upload button. When I select more than one files it uploads and leaves rest of the files. Here is my code:

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


推荐答案

MultiSelect 属性 OpenFileDialog true ,然后使用 FileNames 属性来获取所有选定的文件。

Set MultiSelect property of OpenFileDialog to true and then use FileNames property to get all selected files.

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




FileNames

获取所有文件的文件名

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

例如,您的代码可能如下所示:

For example your code may be like this:

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

这样,您可以显示一条消息,通知用户他上传的文件,其中一个无法上传。

This way you can show a message that informs the user about his uploaded files or which one of them that is failed to upload.

这篇关于如何在c#windows应用程序上传多个文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆