2010年7月5日 星期一

利用Windows Service來自動搬移檔案

原出處
Sample:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Diagnostics;
using System.IO;
using System.Configuration;
using System.Collections;

namespace test_WindowsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

public static EventLog eventLog = new EventLog();

private void button1_Click(object sender, EventArgs e)
{
if (!EventLog.SourceExists("WindowService"))
{
EventLog.CreateEventSource("WindowService", "WindowService_Log");
}
eventLog.Source = "WindowService";
eventLog.Log = "WindowService_Log";

string p_ath = "C:\\";

FileSystemWatcher[] MyWatcher = new FileSystemWatcher[ConfigurationManager.AppSettings.Count];
int i = 0;

foreach (string fname in ConfigurationManager.AppSettings.Keys)
{
MyWatcher[i] = new FileSystemWatcher();
MyWatcher[i].Path = p_ath;
MyWatcher[i].Filter = fname;
MyWatcher[i].NotifyFilter = NotifyFilters.LastWrite | NotifyFilters.DirectoryName | NotifyFilters.FileName;
MyWatcher[i].Created += new FileSystemEventHandler(OnChanged);
MyWatcher[i].IncludeSubdirectories = false;
MyWatcher[i].EnableRaisingEvents = true;
i++;
}
}

private static void OnChanged(object source, FileSystemEventArgs e)
{
eventLog.WriteEntry("Move file: " + e.FullPath + " " + e.ChangeType);
string key = "*." + e.FullPath.Substring(e.FullPath.LastIndexOf('.') + 1);

string DTime = DateTime.Today.ToString("yyyy-MM-dd");
string filename = ConfigurationManager.AppSettings[key] & DTime & e.Name;

if (!e.FullPath.Equals(filename) && File.Exists(e.FullPath))
{

File.Move(e.FullPath, filename);
}
}
}
}

沒有留言:

張貼留言