239 أسطر
8.1 KiB
C#
239 أسطر
8.1 KiB
C#
using System;
|
|
using System.Diagnostics;
|
|
using System.IO;
|
|
using System.Security.Principal;
|
|
using System.Threading;
|
|
using System.Threading.Tasks;
|
|
using System.Windows.Forms;
|
|
using Microsoft.Win32.TaskScheduler;
|
|
using Pingerino.Services.Interfaces;
|
|
|
|
namespace Pingerino.Services
|
|
{
|
|
public class SystemService : ISystemService
|
|
{
|
|
private readonly ILoggingService _logger;
|
|
private bool _disposed;
|
|
|
|
public SystemService(ILoggingService logger)
|
|
{
|
|
_logger = logger ?? throw new ArgumentNullException(nameof(logger));
|
|
}
|
|
|
|
public async System.Threading.Tasks.Task<bool> CleanTemporaryFilesAsync(IProgress<int> progress = null, CancellationToken cancellationToken = default)
|
|
{
|
|
try
|
|
{
|
|
_logger.LogInformation("Starting temporary files cleanup");
|
|
|
|
var folders = new[]
|
|
{
|
|
Environment.ExpandEnvironmentVariables(@"%systemroot%\temp"),
|
|
Environment.ExpandEnvironmentVariables(@"%systemroot%\Prefetch"),
|
|
Environment.ExpandEnvironmentVariables(@"%userprofile%\LocalS~1\Temp"),
|
|
Environment.ExpandEnvironmentVariables(@"%userprofile%\AppData\Local\Temp")
|
|
};
|
|
|
|
int totalSteps = folders.Length * 2;
|
|
int currentStep = 0;
|
|
|
|
foreach (var folder in folders)
|
|
{
|
|
if (cancellationToken.IsCancellationRequested)
|
|
return false;
|
|
|
|
await CleanFolderAsync(folder, progress, currentStep, totalSteps);
|
|
currentStep += 2;
|
|
}
|
|
|
|
progress?.Report(100);
|
|
_logger.LogInformation("Temporary files cleanup completed");
|
|
return true;
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
_logger.LogError("Error during temporary files cleanup", ex);
|
|
return false;
|
|
}
|
|
}
|
|
|
|
private async System.Threading.Tasks.Task CleanFolderAsync(string folderPath, IProgress<int> progress, int currentStep, int totalSteps)
|
|
{
|
|
try
|
|
{
|
|
if (!Directory.Exists(folderPath))
|
|
return;
|
|
|
|
var dirInfo = new DirectoryInfo(folderPath);
|
|
|
|
// Delete files
|
|
await System.Threading.Tasks.Task.Run(() =>
|
|
{
|
|
foreach (var file in dirInfo.GetFiles())
|
|
{
|
|
try
|
|
{
|
|
file.Delete();
|
|
}
|
|
catch
|
|
{
|
|
// Ignore individual file deletion errors
|
|
}
|
|
}
|
|
});
|
|
|
|
progress?.Report((currentStep + 1) * 100 / totalSteps);
|
|
|
|
// Delete directories
|
|
await System.Threading.Tasks.Task.Run(() =>
|
|
{
|
|
foreach (var dir in dirInfo.GetDirectories())
|
|
{
|
|
try
|
|
{
|
|
dir.Delete(true);
|
|
}
|
|
catch
|
|
{
|
|
// Ignore individual directory deletion errors
|
|
}
|
|
}
|
|
});
|
|
|
|
progress?.Report((currentStep + 2) * 100 / totalSteps);
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
_logger.LogWarning($"Error cleaning folder {folderPath}: {ex.Message}");
|
|
}
|
|
}
|
|
|
|
public async System.Threading.Tasks.Task<bool> CreateStartupTaskAsync(string taskName, string executablePath)
|
|
{
|
|
try
|
|
{
|
|
using (var ts = new TaskService())
|
|
{
|
|
var td = ts.NewTask();
|
|
|
|
td.RegistrationInfo.Description = taskName;
|
|
td.Principal.RunLevel = TaskRunLevel.Highest;
|
|
td.Principal.LogonType = TaskLogonType.InteractiveToken;
|
|
td.Triggers.Add(new LogonTrigger());
|
|
|
|
var execAction = new ExecAction(executablePath)
|
|
{
|
|
WorkingDirectory = Path.GetDirectoryName(executablePath)
|
|
};
|
|
td.Actions.Add(execAction);
|
|
|
|
var currentUserName = WindowsIdentity.GetCurrent().Name;
|
|
ts.RootFolder.RegisterTaskDefinition(taskName, td, TaskCreation.CreateOrUpdate,
|
|
currentUserName, null, TaskLogonType.InteractiveToken);
|
|
|
|
_logger.LogInformation($"Startup task '{taskName}' created successfully");
|
|
return await System.Threading.Tasks.Task.FromResult(true);
|
|
}
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
_logger.LogError($"Error creating startup task '{taskName}'", ex);
|
|
return await System.Threading.Tasks.Task.FromResult(false);
|
|
}
|
|
}
|
|
|
|
public async System.Threading.Tasks.Task<bool> RemoveStartupTaskAsync(string taskName)
|
|
{
|
|
try
|
|
{
|
|
using (var ts = new TaskService())
|
|
{
|
|
ts.RootFolder.DeleteTask(taskName, false);
|
|
|
|
_logger.LogInformation($"Startup task '{taskName}' removed successfully");
|
|
return await System.Threading.Tasks.Task.FromResult(true);
|
|
}
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
_logger.LogError($"Error removing startup task '{taskName}'", ex);
|
|
return await System.Threading.Tasks.Task.FromResult(false);
|
|
}
|
|
}
|
|
|
|
public async System.Threading.Tasks.Task<bool> IsStartupTaskExistsAsync(string taskName)
|
|
{
|
|
try
|
|
{
|
|
using (var ts = new TaskService())
|
|
{
|
|
var existingTask = ts.GetTask(taskName);
|
|
return await System.Threading.Tasks.Task.FromResult(existingTask != null);
|
|
}
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
_logger.LogError($"Error checking startup task '{taskName}'", ex);
|
|
return await System.Threading.Tasks.Task.FromResult(false);
|
|
}
|
|
}
|
|
|
|
public void OpenNetworkAdaptersControl()
|
|
{
|
|
try
|
|
{
|
|
Process.Start("control", "ncpa.cpl");
|
|
_logger.LogInformation("Opened network adapters control panel");
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
_logger.LogError("Error opening network adapters control panel", ex);
|
|
}
|
|
}
|
|
|
|
public async System.Threading.Tasks.Task<bool> RunExternalScriptAsync(string scriptPath)
|
|
{
|
|
try
|
|
{
|
|
if (!File.Exists(scriptPath))
|
|
{
|
|
_logger.LogWarning($"Script not found: {scriptPath}");
|
|
return false;
|
|
}
|
|
|
|
var processInfo = new ProcessStartInfo
|
|
{
|
|
FileName = scriptPath,
|
|
UseShellExecute = true
|
|
};
|
|
|
|
using (var process = Process.Start(processInfo))
|
|
{
|
|
if (process == null)
|
|
{
|
|
_logger.LogError("Failed to start external script");
|
|
return false;
|
|
}
|
|
|
|
process.WaitForExit();
|
|
|
|
var success = process.ExitCode == 0;
|
|
_logger.LogInformation($"External script execution completed with exit code: {process.ExitCode}");
|
|
return success;
|
|
}
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
_logger.LogError($"Error running external script: {scriptPath}", ex);
|
|
return false;
|
|
}
|
|
}
|
|
|
|
public void Dispose()
|
|
{
|
|
if (_disposed) return;
|
|
_disposed = true;
|
|
}
|
|
}
|
|
}
|