-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFileMonitoringService.cs
More file actions
161 lines (133 loc) · 5.36 KB
/
Copy pathFileMonitoringService.cs
File metadata and controls
161 lines (133 loc) · 5.36 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
using System;
using System.IO;
using System.ServiceProcess;
using System.Threading;
using System.Configuration;
namespace FileMonitoringService
{
public partial class FileMonitoringService : ServiceBase
{
private FileSystemWatcher fileWatcher;
private string sourceFolder;
private string destinationFolder;
private string logFolder;
public FileMonitoringService()
{
InitializeComponent();
//Read folder paths from App.config
sourceFolder = ConfigurationManager.AppSettings["SourceFolder"];
destinationFolder = ConfigurationManager.AppSettings["DestinationFolder"];
logFolder = ConfigurationManager.AppSettings["LogFolder"];
//Handle missing or empty configuration values
if(string.IsNullOrEmpty(sourceFolder))
{
sourceFolder = @"C:\FileMonitoring\Source"; //Default source folder
Log("SourceFolder is missing in app.config Using default: " + sourceFolder);
}
if(string.IsNullOrEmpty(destinationFolder))
{
destinationFolder = @"C:\FileMonitoring\Destination";// Dfault destination folder
Log("DestinationFolder is missing in App.config Using Default" + destinationFolder);
}
if(string.IsNullOrEmpty (logFolder))
{
logFolder = @"C:\FileMonitoring\Logs";
Log("LogFolder is missing in App.config Using Default: " + logFolder);
}
//Ensure directories exist
Directory.CreateDirectory(sourceFolder);
Directory.CreateDirectory(destinationFolder);
Directory.CreateDirectory (logFolder);
}
protected override void OnStart(string[] args)
{
Log("Service Started.");
//initialize fileSystemWatcher
fileWatcher = new FileSystemWatcher
{
Path = sourceFolder,
Filter = "*.*",
EnableRaisingEvents = true,
IncludeSubdirectories = false
};
fileWatcher.Created += OnFileCreated;
Log("File monitoring started on folder: " + sourceFolder);
}
protected override void OnStop()
{
fileWatcher.EnableRaisingEvents = false;
fileWatcher.Dispose();
Log("Service Stopped.");
}
private void OnFileCreated(object sender, FileSystemEventArgs e)
{
// Ignore temporary files that start with a period or end with a .tmp extension to prevent phantom errors
if (e.Name.StartsWith("~") || e.Name.EndsWith(".tmp", StringComparison.OrdinalIgnoreCase))
return;
try
{
Log($"File detected:{e.FullPath}");
// Addressing the file locking issue (waiting until the source system has finished writing the file completely)
if (!IsFileReady(e.FullPath))
{
Log($"File is locked or still being written: {e.FullPath}");
return;
}
//Generate GUID prepaer new file name
string newFileName = $"{Guid.NewGuid()}{Path.GetExtension(e.Name)}";
string destnationFile = Path.Combine(destinationFolder, newFileName);
//move and rename the file
File.Move(e.FullPath, destnationFile);
//Log success
Log($"File moved: {e.FullPath} -> {destnationFile}");
}catch (Exception ex)
{
Log($"Error processing file: {e.FullPath}. Exception: {ex.Message}");
}
}
// دالة التأكد من أن الملف أصبح جاهزاً للقراءة وغير مقفول من عملية أخرى
private bool IsFileReady(string filePath)
{
const int maxRetries = 10;
const int delayMilliseconds = 500;
for (int i = 0; i < maxRetries; i++)
{
try
{
using (FileStream stream = File.Open(filePath, FileMode.Open, FileAccess.Read, FileShare.None))
{
if (stream.Length > 0)
return true;
}
}
catch (IOException)
{
// The file is still locked, wait a little while and then try again
Thread.Sleep(delayMilliseconds);
}
catch (UnauthorizedAccessException)
{
Thread.Sleep(delayMilliseconds);
}
}
return false;
}
private void Log(string message)
{
string logFilePath = Path.Combine(logFolder,"ServiceLog.txt" );
string logMessage = $"[{DateTime.Now:yyy-MM-dd HH:mm:ss}] {message}\n";
File.AppendAllText(logFilePath,logMessage);
if(Environment.UserInteractive)
{
Console.WriteLine(logMessage);
}
}
public void StartInConsole()
{
OnStart(null);
Console.WriteLine("Starting service in console mode...");
Console.ReadLine();
OnStop();
}
}
}