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

时间:2013-06-20 11:37:44

标签: c# filenotfoundexception

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

我尝试了几乎所有东西,但我无法管理它。

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

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

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


            }

        }

    }
}

5 个答案:

答案 0 :(得分:3)

您明确抛出异常:

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

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

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

确保路径存在。

答案 1 :(得分: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!");
}

请参阅this MSDN page for more information

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

<强> EDIT2 : 这是一个很有用的功能:

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

Edit3 :要查看是否存在权限问题,请查看this which contains some simple code to differentiate between Directory Exists and Access Permissions

答案 2 :(得分:1)

这条线错了。

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

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

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

Directory.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;
    }

答案 3 :(得分:0)

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

答案 4 :(得分: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