c#示例-文件夹增量同步备份

2025-09-22 07:07:50

1、新建名称为“文件夹增量备份”的项目,默认项目存在一个FORM,在这里我们就直接用这个FORM的界面做主界面。

c#示例-文件夹增量同步备份

2、调整界面的到合适大小(因内容比较多,这里就不做演示了),并添加相应控件:两个“label”,两个“textBox”,三个"button",一个“folderBrowserDialog”,一个“fileSystemWatcher”,并修改相应控件的TEXT属性,修改效果见图。

c#示例-文件夹增量同步备份

3、将“fileSystemWatcher”的EnableRaisingEvents属性设置为FALSE,其它属性可以为默认,大家也可以根据具体需求做相应修改。

c#示例-文件夹增量同步备份

4、在这一步,界面部分基本完成,接下来我们开始代码部分。首先添加“using System.IO;”引用,因后面需要操作文件夹及文件,“using System.IO;”为操作文件夹及文件的.

c#示例-文件夹增量同步备份

5、增加“备份文件夹”和“目标文件夹”的地址浏览代码:

//按钮一代码

if (folderBrowserDialog1.ShowDialog() == DialogResult.OK)

            {

                textBox1.Text = folderBrowserDialog1.SelectedPath;

            }

//按钮2代码

if (folderBrowserDialog1.ShowDialog() == DialogResult.OK)

            {

                textBox2.Text = folderBrowserDialog1.SelectedPath;

            }

代码大概意思为通过“folderBrowserDialog”控件,选择路径并赋值给对应的“textBox”控件。

c#示例-文件夹增量同步备份

6、开启监控及提示开启成功提示源码:

fileSystemWatcher1.Path = textBox1.Text.Trim();

            fileSystemWatcher1.EnableRaisingEvents = true;

            MessageBox.Show("开启监控成功");

代码说明:指定监控目录,开启监控,弹出提示窗体表示开启成功。

c#示例-文件夹增量同步备份

7、增加文件复制的方法,具体代码如下:

        public void CopyDirectory(string sourceDirName, string destDirName)

        {

            try

            {

                if (!Directory.Exists(destDirName))

                {

                    Directory.CreateDirectory(destDirName);

                    File.SetAttributes(destDirName, File.GetAttributes(sourceDirName));

                }

                if (destDirName[destDirName.Length - 1] != Path.DirectorySeparatorChar)

                    destDirName = destDirName + Path.DirectorySeparatorChar;

                string[] files = Directory.GetFiles(sourceDirName);

                foreach (string file in files)

                {

                    if (File.Exists(destDirName + Path.GetFileName(file)))

                        continue;

                    File.Copy(file, destDirName + Path.GetFileName(file), true);

                    File.SetAttributes(destDirName + Path.GetFileName(file), FileAttributes.Normal);

                }

                string[] dirs = Directory.GetDirectories(sourceDirName);

                foreach (string dir in dirs)

                {

                    CopyDirectory(dir, destDirName + Path.GetFileName(dir));

                }

            }

            catch (Exception ex)

            {

                StreamWriter sw = new StreamWriter(Application.StartupPath + "\\log.txt", true);

                sw.Write(ex.Message + "     " + DateTime.Now + "\r\n");

                sw.Close();

            }

        }  

复制文件的具体说明,在这里就不做描述了,大家关注下一篇关于文件复制的详细方法文章吧!

c#示例-文件夹增量同步备份

8、在“fileSystemWatcher”的增删改查状态变化中增加文件夹复制备份的方法调用,

 CopyDirectory(textBox1.Text.Trim(), textBox2.Text.Trim());

c#示例-文件夹增量同步备份

9、点击测试按钮,运行程序,运行后效果见图.

c#示例-文件夹增量同步备份

声明:本网站引用、摘录或转载内容仅供网站访问者交流或参考,不代表本站立场,如存在版权或非法内容,请联系站长删除,联系邮箱:site.kefu@qq.com。
猜你喜欢