简体   繁体   中英

Can you help me CopyFileDialog windows form

Hello I have created a program that contains a btnCopy associated with a copyfiledialog, I would like to know why when I press the btnCopy it copies me several files at the same time, I would like that it copies the files one after the other, can will you help me?

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 this:

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);
        }
    }
}

Note that you need to add a reference to Microsoft.VisualBasic to gain access to FileSystem.CopyFile() which copies with the standard windows UI.

可控硅

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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