public Service1()
{
InitializeComponent();
}
protected override void OnStart(string[] args)
{
try
{
Print();
}
catch (Exception ex)
{
File.AppendAllText(@"C:\fold1\Log.txt", ex.ToString());
}
}
public static void Print()
{
//Print & Move the files after printing
DirectoryInfo sourceinfo = new DirectoryInfo(@"C:\fold");
DirectoryInfo target = new DirectoryInfo(@"C:\fold1");
foreach (FileInfo fi in sourceinfo.GetFiles())
{
if (fi.Length != 0)
{
System.Diagnostics.Process process = new System.Diagnostics.Process();
process.StartInfo.CreateNoWindow = true;
process.StartInfo.Verb = "print";
process.StartInfo.FileName = fi.FullName;
process.StartInfo.UseShellExecute = true;
process.StartInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
process.Start();
if (!process.WaitForExit(10000))
process.Kill();
}
MoveFile(fi.FullName);
}
}
public static void MoveFile(string Filename)
{
string SourcePath = @"C:\fold";
string targetpath = @"C:\fold1";
if (!Directory.Exists(targetpath))
{
Directory.CreateDirectory(targetpath);
}
string[] sourceFiles = Directory.GetFiles(SourcePath);
foreach (string sourcefile in sourceFiles)
{
string mfilename = Path.GetFullPath(sourcefile);
string mname = Path.GetFileName(sourcefile);
if (mfilename == Filename)
{
string distnition = Path.Combine(targetpath, mname);
File.Move(mfilename, distnition);
}
}
}
protected override void OnStop()
{ try
{
//Move the files after printing
DirectoryInfo sourceinfo = new DirectoryInfo(@"C:\fold");
DirectoryInfo target = new DirectoryInfo(@"C:\fold1");
foreach (FileInfo fi in sourceinfo.GetFiles())
{
// File.AppendAllText(@"C:\fold1\stop.txt", "Stop method");
MoveFile(fi.FullName);
}
}
catch (Exception ex)
{
File.AppendAllText(@"C:\fold1\Log.txt", ex.ToString());
}
}
I created a service that silently prints files in a given directory and then move them to another one , it worked fine when I started it on the first try but it doesn't run constantly , I want it to print and move any file that is copied into that directory , so what do I have to do? please note that I'm still a begginner in c# and that I cannot quite understand if your explanation it's too complicated , thank you