日期:2014-05-18  浏览次数:20960 次

检测U盘插入并自动复制U盘里文件到D盘 C#源码
各位高手帮帮这个怎样做,检测U盘插入并自动复制U盘里文件到D盘的源码
1.功能检测U盘
2.把U盘的文件COPY到硬盘
大体就是这样的

------解决方案--------------------
C# code
using System; 
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Configuration;
using MTClient.Utility;
using System.Threading;

namespace UDiskMonitor
{
  public partial class MainForm : Form
  {
    bool isCopy = false;
    bool isCopyEnd = false;
    string targetdir = null;

    public const int WM_DEVICECHANGE = 0x219;
    public const int DBT_DEVICEARRIVAL = 0x8000;
    public const int DBT_CONFIGCHANGECANCELED = 0x0019;
    public const int DBT_CONFIGCHANGED = 0x0018;
    public const int DBT_CUSTOMEVENT = 0x8006;
    public const int DBT_DEVICEQUERYREMOVE = 0x8001;
    public const int DBT_DEVICEQUERYREMOVEFAILED = 0x8002;
    public const int DBT_DEVICEREMOVECOMPLETE = 0x8004;
    public const int DBT_DEVICEREMOVEPENDING = 0x8003;
    public const int DBT_DEVICETYPESPECIFIC = 0x8005;
    public const int DBT_DEVNODES_CHANGED = 0x0007;
    public const int DBT_QUERYCHANGECONFIG = 0x0017;
    public const int DBT_USERDEFINED = 0xFFFF;

    public MainForm()
    {
      InitializeComponent();
    }

    private void MainForm_Load(object sender, EventArgs e)
    {

    }

    private void CopyFile(string path)
    {
      isCopyEnd = true;
      if (isCopy)
      {
        DirectoryHelper dir = new DirectoryHelper();
        targetdir = DateTime.Now.ToString();
        targetdir = targetdir.Replace(':', '-');
        targetdir = ConfigReader.GetValue("targetdir") + targetdir;
        //ConfigurationManager.AppSettings["targetdir"].ToString() + targetdir;
        if (!Directory.Exists(targetdir))
        {
          Directory.CreateDirectory(targetdir);
        }
        else
        {
          listBox1.Items.Add(DateTime.Now.ToString() + "--> 文件夹已经存在,请确认!");
          return;
        }

        dir.CopyDirectoryAndFiles(targetdir, new DirectoryInfo(path));
        listBox1.Items.Add(DateTime.Now.ToString() + "--> 已完成数据拷贝!");
        listBox1.Items.Add(DateTime.Now.ToString() + "--> 正在检查文件合法性!");
        listBox1.Items.Add(DateTime.Now.ToString() + "--> 文件合法!");
        listBox1.Items.Add(DateTime.Now.ToString() + "--> 数据正在入库!");
      }
    }

    protected override void WndProc(ref Message m)
    {
      try
      {
        if (m.Msg == WM_DEVICECHANGE)