【问题标题】:Can you help me CopyFileDialog windows form你能帮我复制文件对话框窗体吗
【发布时间】:2020-02-24 17:59:56
【问题描述】:

您好,我创建了一个包含与 copyfiledialog 关联的 btnCopy 的程序,我想知道为什么当我按下 btnCopy 时它会同时复制几个文件,我希望它在其他,你能帮帮我吗?

private void btnCopy_Click(object sender,EventArgs e)
{
  string sourceDir = @"C:\Users\PORTABLEHP\Documents";
  string destDir = @"C:\Users\PORTABLEHP\Documents\xgen";

  try 
  {
    string [] txtList = Directory.GetFiles(sourceDir,"*.txt");

    foreach (string f in txtList)
    {
      try
      {
        string fName = f.Substring(sourceDir.Length + 1);
        string [] files = new string[sourceDir.Length];

        progressBar1.Value = 1;
        progressBar1.Minimum = 0;
        progressBar1.Maximum = files.Length;

        for(int i = 1;i < files.Length; i++)
        {
          progressBar1.PerformStep();

          File.Copy(Path.Combine(sourceDir,fName),
                    Path.Combine(destDir,fName), true);
        }
      }
      catch(IOException copyerror)
      {
        MessageBox.Show(copyerror.Message)
      }

,

【问题讨论】:

  • 外面try/catch的意义何在?此外,您的代码缺少 catch() 部分。
  • 也许我没看错……但是files 数组和内部循环的意义何在?看起来你在做不必要的工作。
  • 是的,看起来你有一个嵌套循环。

标签: c#


【解决方案1】:

试试这个:

using System;
using System.IO;
using System.Windows.Forms;
using Microsoft.VisualBasic.FileIO;

public partial class Form1 : Form
{
    // other code

    private void button1_Click(object sender, EventArgs e)
    {
        string sourceDir = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
        string destDir = Path.Combine(sourceDir, "xgen");

        string[] txtList =
            Directory.GetFiles(sourceDir, "*.txt");

        progressBar1.Value = 1;
        progressBar1.Minimum = 0;
        progressBar1.Maximum = txtList.Length;

        try
        {
            foreach (string f in txtList)
            {
                string fName = Path.GetFileName(f);   //f.Substring(sourceDir.Length + 1);
                string destFile = Path.Combine(destDir, fName);

                FileSystem.CopyFile(
                    f, destFile, UIOption.AllDialogs, UICancelOption.ThrowException);

                progressBar1.PerformStep();
            }
        }
        catch (IOException copyerror)
        {
            MessageBox.Show(copyerror.Message);
        }
    }
}

请注意,您需要添加对 Microsoft.VisualBasic 的引用才能访问使用标准 Windows UI 复制的 FileSystem.CopyFile()。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-01-05
    • 2012-12-17
    • 1970-01-01
    • 2016-01-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多