-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathProgram.cs
More file actions
215 lines (182 loc) · 7.39 KB
/
Program.cs
File metadata and controls
215 lines (182 loc) · 7.39 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
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
using System.Net.NetworkInformation;
using System.Runtime.InteropServices;
using Microsoft.Win32;
using System.Drawing.Printing;
namespace PrinterMapper
{
class Program
{
private static string? logFilePath;
static void Main(string[] args)
{
string appDataPath = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
string logDirectory = Path.Combine(appDataPath, "PrinterMapper");
Directory.CreateDirectory(logDirectory);
logFilePath = Path.Combine(logDirectory, "log.txt");
if (File.Exists(logFilePath))
{
File.WriteAllText(logFilePath, string.Empty);
}
LogMessage("PrinterMapper application started");
try
{
using (RegistryKey? key = Registry.CurrentUser.OpenSubKey(@"Software\PrinterMapper"))
{
if (key == null)
{
LogMessage("ERROR: Registry key not found");
return;
}
object? managedPrintServerObj = key.GetValue("ManagedPrintServer");
string? managedPrintServer = managedPrintServerObj?.ToString();
if (string.IsNullOrEmpty(managedPrintServer))
{
LogMessage("ERROR: ManagedPrintServer value not found or empty");
return;
}
LogMessage($"Found ManagedPrintServer: {managedPrintServer}");
if (!TestServerConnectivity(managedPrintServer))
{
LogMessage($"ERROR: Print server '{managedPrintServer}' is not accessible");
return;
}
LogMessage($"Print server '{managedPrintServer}' is accessible");
HashSet<string> desiredPrinters = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
foreach (string valueName in key.GetValueNames())
{
if (valueName.Equals("ManagedPrintServer", StringComparison.OrdinalIgnoreCase))
continue;
string? printerPath = key.GetValue(valueName)?.ToString();
if (!string.IsNullOrEmpty(printerPath))
{
desiredPrinters.Add(printerPath);
}
}
List<string> installedPrinters = GetInstalledPrintersFromServer(managedPrintServer);
foreach (string printer in installedPrinters)
{
if (!desiredPrinters.Contains(printer))
{
LogMessage($"Removing old printer: {printer}");
bool removed = RemovePrinter(printer);
LogMessage(removed ? $"Successfully removed {printer}" : $"Failed to remove {printer}");
}
}
int successCount = 0;
foreach (string printerPath in desiredPrinters)
{
LogMessage($"Processing printer: {printerPath}");
if (MapPrinter(printerPath))
{
successCount++;
LogMessage($"Successfully mapped printer: {printerPath}");
}
else
{
LogMessage($"Failed to map printer: {printerPath}");
}
}
LogMessage($"Printer mapping completed. {successCount}/{desiredPrinters.Count} printers mapped successfully");
}
}
catch (Exception ex)
{
LogMessage($"ERROR: {ex.Message}");
}
LogMessage("PrinterMapper application finished");
}
#region Native Printer API (Winspool)
[DllImport("winspool.drv", CharSet = CharSet.Unicode, SetLastError = true)]
private static extern bool AddPrinterConnection(string pName);
[DllImport("winspool.drv", CharSet = CharSet.Unicode, SetLastError = true)]
private static extern bool DeletePrinterConnection(string pName);
#endregion
#region Printer Listing
private static List<string> GetInstalledPrintersFromServer(string serverName)
{
List<string> printers = new List<string>();
try
{
LogMessage($"Querying installed printers from server: {serverName}");
foreach (string printerName in PrinterSettings.InstalledPrinters)
{
if (printerName.StartsWith($"\\\\{serverName}\\", StringComparison.OrdinalIgnoreCase))
{
printers.Add(printerName);
LogMessage($"Found installed printer: {printerName}");
}
}
}
catch (Exception ex)
{
LogMessage($"Error enumerating printers: {ex.Message}");
}
return printers;
}
#endregion
#region Printer Add/Remove
private static bool MapPrinter(string printerPath)
{
try
{
bool result = AddPrinterConnection(printerPath);
if (!result)
{
int error = Marshal.GetLastWin32Error();
LogMessage($"Failed to map printer {printerPath}, error code: {error}");
}
return result;
}
catch (Exception ex)
{
LogMessage($"Exception mapping printer {printerPath}: {ex.Message}");
return false;
}
}
private static bool RemovePrinter(string printerPath)
{
try
{
bool result = DeletePrinterConnection(printerPath);
if (!result)
{
int error = Marshal.GetLastWin32Error();
LogMessage($"Failed to remove printer {printerPath}, error code: {error}");
}
return result;
}
catch (Exception ex)
{
LogMessage($"Exception removing printer {printerPath}: {ex.Message}");
return false;
}
}
#endregion
#region Connectivity + Logging
private static bool TestServerConnectivity(string serverName)
{
try
{
using (Ping ping = new Ping())
{
PingReply reply = ping.Send(serverName, 3000);
return reply.Status == IPStatus.Success;
}
}
catch { return false; }
}
private static void LogMessage(string message)
{
string logEntry = $"{DateTime.Now:yyyy-MM-dd HH:mm:ss} - {message}";
try
{
if (!string.IsNullOrEmpty(logFilePath))
{
File.AppendAllText(logFilePath, logEntry + Environment.NewLine);
}
}
catch { }
}
#endregion
}
}