111,098
社区成员




using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Xml;
using System.Configuration;
using System.Data;
using System.Diagnostics;
using System.ServiceProcess;
using System.Text;
using System.IO;
using System.Threading;
namespace DataTransfer
{
public partial class Service1 : ServiceBase
{
public Service1()
{
InitializeComponent();
if (!System.Diagnostics.EventLog.SourceExists("DataTransferSource"))
{
System.Diagnostics.EventLog.CreateEventSource("DataTransferSource", "DataTransfer");
}
bw = new BackgroundWorker();
bw.DoWork += new DoWorkEventHandler(bw_DoWork);
bw.RunWorkerCompleted += new RunWorkerCompletedEventHandler(bw_RunWorkerCompleted);
}
protected override void OnStart(string[] args)
{
string mDateTime = DateTime.Now.ToString();
eventLog1.WriteEntry("DataTransfer Service was started at " + mDateTime);
bw.RunWorkerAsync(args);
}
protected override void OnStop()
{
string mDateTime = DateTime.Now.ToString();
bw.CancelAsync();
while (bw.IsBusy) Thread.Sleep(300000);
eventLog1.WriteEntry("DataTransfer Service was stopped at " + mDateTime);
}
void bw_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
string mDateTime = DateTime.Now.ToString();
eventLog1.WriteEntry("DataTransfer Service was completed at " + mDateTime);
}
void bw_DoWork(object sender, DoWorkEventArgs e)
{
while (!bw.CancellationPending)
{
string mDateTime = DateTime.Now.ToString();
// Trace.WriteLine("DataTransfer: " + new Random().Next().ToString());
// eventLog1.WriteEntry("DataTransfer Service was running at " + mDateTime + "with content " + new Random().Next().ToString());
CopyFile(); // 上面被注释的代码可以执行,但是调用CopyFile()就没办法执行了,日志中追查不到,我看了下文件夹权限问题,应该也不是,因为targetpath的权限是everyone可写,ASPNET可写
Thread.Sleep(300000);
}
}
public void CopyFile()
{
string mDateTime = DateTime.Now.ToString();
string sourcePath = @"D:\Temp\Source\" + DateTime.Now.Date.ToString("yyyyMMdd") + "_Testing-01-A.log";
string targetPath = @"D:\Temp\Source\" + DateTime.Now.Date.ToString("yyyyMMdd") + "_Testing-01-A_" + mDateTime + ".log";
try
{
if (!File.Exists(sourcePath))
{
eventLog1.WriteEntry("The file" + sourcePath + " was not existed at " + mDateTime);
return;
}
if (File.Exists(targetPath))
{
eventLog1.WriteEntry("The file" + targetPath + " was existed at " + mDateTime);
return;
}
File.Copy(sourcePath, targetPath);
eventLog1.WriteEntry("The file was copied to the target path at " + mDateTime);
}
catch (Exception ee)
{ }
}
}
}