如何将文件夹复制到一个目录?

本文关键字:一个 文件夹 复制 | 更新日期: 2023-09-27 18:19:06

如何将文件夹复制到目录?

我几乎什么都试过了,但就是不行。

我从其他问题中得到了例子,但没有一个是有效的。

当我试图让我的应用程序复制一个文件夹时,它给了我一个错误:

File does not exist: C:'Users'Loko'Desktop'dir1'New folder (5)

在这一行:

Stopwatch stopwatch = Stopwatch.StartNew();

这可能与它无关。不管怎样,有人能帮我吗?只是文件夹出了点问题。

这是我的代码:

    using System;
    using System.IO;
    using System.Configuration;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Data;
    using System.Drawing;
    using System.Linq;
    using System.Text;
    using System.Diagnostics;
    using System.Threading;
    using System.Windows.Forms;
    using MySql.Data.MySqlClient;
    namespace ChaloSync
    {
    public partial class Form1 : Form
    {
        private bool pause = false;
        String source = ConfigurationManager.AppSettings[@"Directory1"];
        String target = ConfigurationManager.AppSettings[@"Directory2"];

        public static bool WaitForFileAvailable(string filePath, TimeSpan timeout)
        {
            if (!File.Exists(filePath))
                throw new InvalidOperationException("File does not exist: " + filePath);
            Stopwatch stopwatch = Stopwatch.StartNew();
            while (stopwatch.Elapsed <= timeout)
            {
                try
                {
                    using (new FileStream(filePath, FileMode.Open, FileAccess.Read))
                    {
                        return true;
                    }
                }
                catch { }
                Thread.Sleep(250);
            }
            return false;
        }

        public Form1()
        {
            InitializeComponent();
        }
        static void config()
        {
            foreach (string key in ConfigurationManager.AppSettings)
            {
                string value = ConfigurationManager.AppSettings[key];
                MessageBox.Show(value);
            }
        }
        private void fileSystemWatcher1_Changed(object sender, System.IO.FileSystemEventArgs e)
        {
                listBox1.Items.Add("File changed> " + e.FullPath + " -Date:" + DateTime.Now);
        }
        private void fileSystemWatcher1_Created(object sender, System.IO.FileSystemEventArgs e)
        {
            if (WaitForFileAvailable(e.FullPath, TimeSpan.FromSeconds(10)))
            {
                listBox1.Items.Add("File created> " + e.FullPath + " -Date:" + DateTime.Now);
                File.Copy(e.FullPath, Path.Combine(target, e.Name));
                Directory.GetFiles(e.FullPath, Path.Combine(target, e.Name));
            }
            else // The file failed to become available within 10 seconds.
            {
                // Error handling.
            }
            }
        private void fileSystemWatcher1_Deleted(object sender, System.IO.FileSystemEventArgs e)
        {
                listBox1.Items.Add("File deleted> " + e.FullPath + " -Date:" + DateTime.Now);
                File.Delete(target + e.Name);
        }
        private void fileSystemWatcher1_Renamed(object sender, System.IO.RenamedEventArgs e)
        {
                listBox1.Items.Add("File renamed> " + e.FullPath + " -Date:" + DateTime.Now);
        }
        private void Start_Click(object sender, EventArgs e)
        {
            fileSystemWatcher1.Path = source;
            fileSystemWatcher1.EnableRaisingEvents = false;
            fileSystemWatcher1.EnableRaisingEvents = true;   
            if (!pause)
            {
                pause = true;
                Start.Text = "Pause";
            }
            else
            {
                pause = false;
                Start.Text = "Start";

            }
        }
    }
}

如何将文件夹复制到一个目录?

你显式抛出异常:

 if (!File.Exists(filePath))
            throw new InvalidOperationException("File does not exist: " + filePath);

File.Exists返回false,因为您检查了文件而文件不是目录。你可以试试

Directory.Exists(filePath) || File.Exists(filePath)
路径

确保

根据抛出的错误信息判断,路径不存在。

复制整个目录,使用如下命令:

string sourcePath = @"C:'Users'Public'TestFolder";
string targetPath =  @"C:'Users'Public'TestFolder'SubDir";
if (System.IO.Directory.Exists(sourcePath))
{
    string[] files = System.IO.Directory.GetFiles(sourcePath);
    // Copy the files and overwrite destination files if they already exist. 
    foreach (string s in files)
    {
       // Use static Path methods to extract only the file name from the path.
       fileName = System.IO.Path.GetFileName(s);
       destFile = System.IO.Path.Combine(targetPath, fileName);
       System.IO.File.Copy(s, destFile, true);
    }
}
else
{
    Console.WriteLine("Source path does not exist!");
}

有关更多信息,请参阅此MSDN页面

Edit:正如Tommi所说:使用File。Exists用于检查文件是否存在…使用目录。用于检查路径是否为有效的文件夹/目录。

Edit2 :这是一个有用的函数:

internal static bool FileOrDirectoryExists(string name)
{
   return (Directory.Exists(name) || File.Exists(name))
}

Edit3:检查是否权限问题,看看这个包含一些简单的代码来区分目录存在和访问权限

这一行不对。

Directory.GetFiles(e.FullPath, Path.Combine(target, e.Name));

第一个参数应该是一个路径,而不是一个带文件的路径,第二个参数应该是一个模式,而不是一个完整的路径。

不清楚你在这里想做什么,因为你没有读取返回的值,但它会引发IOException

目录。getfile

然而,您的初始异常是由文件创建仍在进行中引起的。当您收到创建事件时,您会立即做出反应,检查文件是否存在,但此时操作系统不允许您调用此文件。存在(特别是当文件很大时)。尝试在调用测试

之前设置延迟
    public static bool WaitForFileAvailable(string filePath, TimeSpan timeout)
    {
        Stopwatch stopwatch = Stopwatch.StartNew();
        while (stopwatch.Elapsed <= timeout)
        {
            Thread.Sleep(250);
            try
            {
                return File.Exists(filePath);
            }
            catch 
            {  
                // Not a very good thing to do, but I suppose that in the context of 
                // the call from the FileSystemWatcher Created event could be allowed
            }
        }
        return false;
    }

我猜文件夹不存在,或者在复制时删除了。
希望这对你有帮助。
http://www.codeproject.com/Articles/3210/Function-to-copy-a-directory-to-another-place-noth

我认为您的fileSystemWatcher1_Created()方法可以调用更改的文件更改的文件夹

因此,您可能希望以不同的方式处理文件和文件夹,就像这样(您必须修改它以适应-这只是为了让您了解这个想法)。

注意e.FullPath可能是一个文件或它可能是一个文件夹,我们可以看到如果它是一个文件夹使用Directory.Exists():

private void fileSystemWatcher1_Created(object sender, System.IO.FileSystemEventArgs e)
{
    if (Directory.Exists(e.FullPath)) // Is it a folder?
    {
        // Do whatever you want to do with a folder instead of a file.
        // You'll need to check if target is right: It needs to be the name of an exisitng folder.
        CopyDirectories(e.FullPath, target);
    }
    else
    {
        if (WaitForFileAvailable(e.FullPath, TimeSpan.FromSeconds(10)))
        {
            listBox1.Items.Add("File created> " + e.FullPath + " -Date:" + DateTime.Now);
            File.Copy(e.FullPath, Path.Combine(target, e.Name));
        }
        else // The file failed to become available within 10 seconds.
        {
            // Error handling.
        }
    }
}
要复制目录,可以使用如下代码:
public void CopyDirectories(string sourceDir, string destinationDir)
{
    foreach (string dir in Directory.GetDirectories(sourceDir, "*", SearchOption.AllDirectories))
        Directory.CreateDirectory(destinationDir + dir.Substring(sourceDir.Length));
    foreach (string fileName in Directory.GetFiles(sourceDir, "*.*", SearchOption.AllDirectories))
        File.Copy(fileName, destinationDir + fileName.Substring(sourceDir.Length));
}

我从这里得到的:https://stackoverflow.com/a/8022011/106159