如何将文件夹复制到目录?
我几乎尝试了所有东西,但我无法让它工作。
我从其他问题中得到了例子,但没有任何效果。
当我试图让我的应用程序复制一个文件夹时,它给了我一个错误:
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";
}
}
}
}