【发布时间】: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#