首页 > 解决方案 > 将文件从 ListBox 中的路径复制到特定文件夹

问题描述

我正在尝试复制从 a 中选择的文件OpenFileDialog并将其路径保存到ListBox.
从路径到ListBox,我希望它把它复制到一个特定的文件夹中。
到目前为止,它正在将整个源文件夹复制到目标文件夹中。

我的代码:

private void button1_Click(object sender, EventArgs e)
{
    System.IO.Stream myStream;
    OpenFileDialog thisDialog = new OpenFileDialog();

    thisDialog.InitialDirectory = "c:\\";
    thisDialog.Filter = "All files (*.*)|*.*";
    thisDialog.FilterIndex = 2;
    thisDialog.RestoreDirectory = true;
    thisDialog.Multiselect = true;
    thisDialog.Title = "Please Select Attachments!";

    if (thisDialog.ShowDialog() == DialogResult.OK)
    {
        foreach (String file in thisDialog.FileNames)
        {
            try
            {
                if ((myStream = thisDialog.OpenFile()) != null)
                {
                    using (myStream)
                    {
                        listBox1.Items.Add(file);
                    }
                }
            }

            catch (Exception ex)
            {
                MessageBox.Show("Error: Could not read file from disk. Original error: " + ex.Message);
            }
        }
    }
    else
    {
        //do nothing
    }
    //after selecting the files into the openfile dialog proceed to action the below.

    foreach (object item in listBox1.Items)
    {
        //MessageBox.Show(string.Format("{0}!", listBox1.ToString()));
        MessageBox.Show(item.ToString());
        string sourceFolder = item.ToString();
        string destinationFolder = @"c:\\testing";

        //DirectoryInfo directory = new DirectoryInfo(sourceFolder);
        DirectoryInfo directoryName = new DirectoryInfo( Path.GetDirectoryName(sourceFolder));

        FileInfo[] files = directoryName.GetFiles();
        foreach (var file in files)
        {
            string destinationPath = Path.Combine(destinationFolder, file.Name);
            File.Copy(file.FullName, destinationPath);
        }
    }
}

任何帮助都是受欢迎的。谢谢。

标签: c#

解决方案


您正在读取整个源目录的次数与您在文件选择器中选择的文件的数量一样多,但是您已经在ListBox.

string destinationFolder = @"c:\testing";
foreach (var item in listBox1.Items)
{
    string sourcePath = item.ToString();
    string fileName = Path.GetFileName(sourcePath);
    string destinationPath = Path.Combine(destinationFolder, fileName);
    File.Copy(sourcePath, destinationPath);
}

推荐阅读