我正在尝试复制从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);
}
}
}
欢迎任何帮助。谢谢。
答案 0 :(得分: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);
}