c#同步备份文件夹文件(部分案例)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
namespace 同步文件监视测试
{
class Program
{
static string a = @"C:\Users\dell\Desktop\123";
static string d = @"C:\Users\dell\Desktop\备份";
//static string d = @"D:\备份";
static DirectoryInfo fbeifen;
static DirectoryInfo f123 = new DirectoryInfo(a);
static StreamReader rain;//不能放于循环体多次创建,要记住啊!!!
static StreamWriter saout;
static StringBuilder fff = new StringBuilder("");
static FileSystemWatcher w;
static void Main(string[] args)
{
w = new FileSystemWatcher(a);
w.Changed += new FileSystemEventHandler(w_Changed);
//w.NotifyFilter = NotifyFilters.CreationTime | NotifyFilters.LastWrite | NotifyFilters.FileName;
w.EnableRaisingEvents = true;
Console.Read();
}
static void w_Changed(object sender, FileSystemEventArgs e)
{
//此处可避免同时执行两次
w.EnableRaisingEvents = false;
System.Threading.Thread.Sleep(1000);
w.EnableRaisingEvents = true;
fbeifen = new DirectoryInfo(d);//注意这里,不能只用一个对象
// 每次改变都会执行两次不知到为什么
if (!fbeifen.Exists)
{
try
{
fbeifen.Create();
Console.WriteLine("开始创建备份时间" + DateTime.Now.Ticks.ToString());
foreach (var item in f123.GetFiles())
{
rain = new StreamReader(item.DirectoryName + @"\" + item.Name,Encoding.GetEncoding("gb2312"));
File.Create(d + @"\" + item.Name).Close();
saout = File.AppendText(d + @"\" + item.Name);
saout.Write(rain.ReadToEnd());
rain.Close();
saout.Close();
//System.Threading.Thread.Sleep(100);
}
Console.WriteLine("创建备份成功!");
}
catch (Exception ex)
{
Console.WriteLine("创建备份失败!" + ex.Message);
}
}
else
{
try
{
rain = new StreamReader(a + @"\" + e.Name,Encoding.GetEncoding("gb2312"));
File.Create(d + @"\" + e.Name).Close();
saout = File.AppendText(d + @"\" + e.Name);
saout.Write(rain.ReadToEnd());
rain.Close();
saout.Close();
Console.WriteLine(e.Name + "---文件更新备份成功!");
}
catch (Exception ex)
{ Console.WriteLine("文件更新备份失败:" + ex.Message); }
}
}
}
}