简体   繁体   English

将文件从列表框复制到另一个目录

[英]Copy files from listbox to another directory

I'm fairly new to C# and what I'm trying to do is 我对C#相当陌生,我想做的是

  1. Search for a file 搜索文件
  2. List all matching files into a listbox 将所有匹配的文件列出到列表框中
  3. Copy the whole folder where the file is located to another place 将文件所在的整个文件夹复制到另一个位置

I found bits and pieces on the web that I'm using. 我在网络上发现了点点滴滴。 Right now it's only the btn_search_Click part that is working. 现在只有btn_search_Click起作用了。

using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;

namespace WindowsFormsApp1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void btn_search_Click(object sender, EventArgs e)
        {
            try
            {
                listBox1.Items.Clear();
                //Directory to search in
                DirectoryInfo Di = new DirectoryInfo(@"D:\xxxx\Versionen");
                FileInfo[] nPfad = Di.GetFiles(textBox1.Text, SearchOption.AllDirectories);
                Int32 nLengePfad = nPfad.GetLength(0);
                listBox1.Items.AddRange(nPfad);

            }
            catch (Exception)
            {
                MessageBox.Show("File not found");

            }

        }
        private void btn_save_Click(object sender, EventArgs e)
        {
            {
                string sourceFile = @"D:\Users\Public\public\test.txt";
                string destinationFile = @"D:\Users\Public\private\test.txt";

                // To move a file or folder to a new location:
                System.IO.File.Move(sourceFile, destinationFile);

                // To move an entire directory. To programmatically modify or combine
                // path strings, use the System.IO.Path class.
                System.IO.Directory.Move(@"C:\Users\Public\public\test\", @"C:\Users\Public\private");
            }
        }
    }
}

My question now is, what would the code look like, if I want to select a file from the listbox and copy NOT the file but the folder it's located in to another place. 现在我的问题是,如果我想从列表框中选择一个文件,而不是复制文件而是将文件所在的文件夹复制到另一个位置,代码将是什么样子。 I already have set a btn_save and a basic code to move files, but I need someone to show me a way to copy any selected file from the listbox or rather copy the folder of the selected file. 我已经设置了btn_save和用于移动文件的基本代码,但是我需要有人向我展示一种从列表框中复制任何选定文件,或者复制选定文件的文件夹的方法。

I'm fairly new to C# and am open for new approaches. 我对C#相当陌生,并且愿意接受新方法。 If I'm completely wrong with the code, scratch it, show me a correct or easier way to achieve the same 如果我对代码完全不对,请刮掉它,然后向我展示一种实现相同目标的正确或更简单的方法

You can move directly the directory with Directory.Move . 您可以使用Directory.Move直接移动目录

Using the FileInfo.DirectoryName you can get the Directory path from the FileInfo[] SelectedItems. 使用FileInfo.DirectoryName可以从FileInfo[] SelectedItems获取目录路径。

var itemsToMove = myListBox.SelectedItems.Cast<FileInfo>();
var directoriesTheyAreIn = itemsToMove.Select(x => x.DirectoryName);

var cleanDirectoriesList = directoriesTheyAreIn.Distinct();
//As many file can be in the same Dir we only need to move the dire once to move those file.

But what if Dir contains both selected and unselected files? 但是,如果Dir同时包含选定文件和未选定文件,该怎么办? Here I will move them all. 在这里,我将全部移动。

foreach (var path in cleanDirectoriesList)
{
    // here you have to craft your destination directory
    string destinationDirectory = "";
    Directory.Move(path, destinationDirectory);
}

From your question it's unclear what part of the old path should be keep in the new path. 从您的问题来看,不清楚旧路径的哪一部分应保留在新路径中。 but if it's based on your "D:\\xxxx\\Versionen" string you can simply replace this part with the new root path "NewRoot\\foo\\bar" : 但是,如果它基于您的"D:\\xxxx\\Versionen"字符串,则可以简单地新的根路径"NewRoot\\foo\\bar" 替换此部分:

 string destinationDirectory = path.Replace(@"D:\xxxx\Versionen", @"G:\FooBAR\NEWPATH\");

If you need to move only the selected file you can blindly call Directory.CreateDirectory before copying each file, as it won't throw error if the directory already exist. 如果只需要移动选定的文件,则可以在复制每个文件之前盲目调用Directory.CreateDirectory ,因为如果目录已经存在,它不会引发错误。 Grouping on directory to avoid useless instruction could have been possible but I feel like it won't be that easy to modify. 可以对目录进行分组以避免不必要的指令,但是我觉得修改起来并不容易。 Here the code will simply be: create the directory then move the file . 这里的代码将简单地是:创建目录,然后移动文件

foreach (var item in itemsToMove) {
    string destinationDirectory = @"BasedPath\" + " Craft it ";
    Directory.CreateDirectory(destinationDirectory);
    File.Move(item.FullName, destinationDirectory + item.Name);
}

Store the list of files into a List<FileInfo> and iterate through with foreach . 将文件列表存储到List<FileInfo>并使用foreach进行遍历。 This worked for me: 这为我工作:

        string destination = @"C:\Some\Destination\";
        string actualFile = string.Empty;
        foreach (var file in fileList)
        {
            actualFile = file.FullName;
            File.Copy(actualFile, destination + Path.GetFileName(actualFile));
        }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM