c# - 将文件从 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);
}
}
}
任何帮助都是受欢迎的。谢谢。
解决方案
您正在读取整个源目录的次数与您在文件选择器中选择的文件的数量一样多,但是您已经在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);
}
推荐阅读
- node.js - 使用 lambda 发送邮件时的 AWS SES 服务问题
- laravel - Laravel 质量分配受保护的字段
- python - 使用来自另一个 Dataframe 的索引替换 Dataframe 中的行
- r - 在R中循环制作数据集
- python - 将数据帧与时间序列数据合并+检查第一个df中是否已经存在值
- caching - dask 缓存延迟函数示例
- r - 在 R 中加入数据帧时行重复的问题
- java - 将未知的泛型类型保存到集合并恢复特定类型
- c# - 我在 C# 中收到 System.ArgumentOutOfRangeException 错误?
- php - WP数据库错误“字段列表”中的未知列“wp_”用于查询SELECT wp_