0

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

我几乎尝试了所有东西,但我无法让它工作。

我从其他问题中得到了例子,但没有任何效果。

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

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";


            }

        }

    }
}
4

5 回答 5

3

You throw exception explicitly:

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

File.Exists return false, because you check file and file is not directory. You can try

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

to ensure that path exists.

于 2013-06-20T11:43:52.150 回答
2

从错误消息来看,您抛出的路径不存在。

要复制整个目录,请使用以下命令:

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 页面

编辑:正如 Tommi 所说:使用 File.Exists 检查文件是否存在......使用 Directory.Exists 检查路径是否是有效的文件夹/目录。

Edit2:这是一个有用的功能:

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

Edit3:要检查这是否是权限问题,请查看此内容,其中包含一些用于区分目录存在和访问权限的简单代码

于 2013-06-20T11:41:23.447 回答
1

这条线是错误的。

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

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

目前尚不清楚您在这里尝试做什么,因为您没有读取返回的值,但就目前而言,它会引发 IOException

目录.GetFiles

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

    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;
    }
于 2013-06-20T11:50:01.900 回答
0

我认为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

于 2013-06-20T11:56:13.857 回答
0

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

于 2013-06-20T11:49:20.637 回答