【问题标题】:Copy file from path in ListBox to a specific folder将文件从 ListBox 中的路径复制到特定文件夹
【发布时间】:2018-11-16 11:36:10
【问题描述】:

我正在尝试复制我从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);
        }
    }
}

非常欢迎任何帮助。谢谢。

【问题讨论】:

  • It is pasting the entire source folder into the destination folder. 你能解释一下,换句话说,如果不是那你想让它做什么?
  • 如果从 openfiledialog 中选择桌面上的文件。它正在复制在桌面上找到的所有项目并将其粘贴到目标文件夹中。即 c:\\testing
  • 您正在使用所选文件的路径,然后调用GetFiles() 以获取该目录中的文件列表,然后将该路径中的文件复制到目标路径。如果你不想那样,你为什么要这样做?这是您从其他答案/网站中捞出的一些代码,但您真的不知道它的作用吗?您可以使用在每个 ListBox 项目中找到的文件名复制文件,然后使用该引用执行复制。

标签: c#


【解决方案1】:

您正在读取整个源目录的次数是您在文件选择器中选择的文件数的两倍,但是您已经在 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);
}

【讨论】:

猜你喜欢
  • 2018-03-11
  • 1970-01-01
  • 1970-01-01
  • 2020-08-15
  • 1970-01-01
  • 2016-10-23
  • 2017-04-24
  • 2018-05-17
  • 1970-01-01
相关资源
最近更新 更多