【问题标题】:In C# how can I get names of files from a checkListBox and move the files?在 C# 中,如何从 checkListBox 获取文件名并移动文件?
【发布时间】:2015-10-22 05:21:43
【问题描述】:

在 C# 中,我需要知道如何使用 checkListBox 中的项目名称作为文件路径,以便用户可以选择文件名,然后单击一个按钮,将这些文件移动到电脑上的另一个文件位置。我已经知道如何让文件出现在checkListBox 中,但我不知道如何检测checkListBox 中的文件路径,以便用户可以移动checkListBox 中列出的选定文件。

如果有帮助,这是一种更好的表达方式。我想在列表框中获取列出的文件,然后对它们做一些事情。

void sendbtn_Click(object sender, EventArgs e)
        {
            string destinationFolder = gamedir.Text;
            string[] files = Directory.GetFiles(checkListView1.SelectedItems);
            foreach(var file in files)
            {
                string destinationPath = Path.Combine(destinationFolder, file);
                File.Copy(file.Fullname, destinationPath);
            }
        }

【问题讨论】:

  • 你能发布一些代码吗?这总是有帮助的:)

标签: c# file checklistbox


【解决方案1】:

你可以使用System.IO.Directory

  • 目录列表:

    Directory.GetDirectories

  • 目录下的文件列表

    Directory.GetFiles("Path");

  • 文件完整路径:

    System.IO.Path.GetFileName

  • 移动文件

    Directory.Move

【讨论】:

    【解决方案2】:

    创建包含文件路径和可选文件名的结构以缩短 ComboBox 中的项目:

    struct ComboItem {
        public string FileName { get; set; }
        public string FilePath { get; set; }
    
        public override string ToString() {
            return FileName;
        }
    }
    

    覆盖 ToString() 会变魔术 - 在 ComboBox 中,您只会看到文件名。像这样填充 ComboBox:

    void FillCombo() {
        var startPath = @"your path";
        comboBox1.Items.Clear();
        foreach (var file in Directory.GetFiles(startPath)) {
            var item = new ComboItem {
                FilePath = file,
                FileName = Path.GetFileName(file)
            };
            comboBox1.Items.Add(item);
        }
    }
    

    然后在移动操作中获取所选项目:

    var item = (ComboItem)comboBox1.SelectedItem;
    

    在项目中你有文件名和文件路径。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-12-19
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多