WGet.NET 4.4.1
A WinGet wrapper library for .Net.
Loading...
Searching...
No Matches
WinGet.cs
1//--------------------------------------------------//
2// Created by basicx-StrgV //
3// https://github.com/basicx-StrgV/ //
4//--------------------------------------------------//
5using System;
6using System.Collections.Generic;
7using System.IO;
8using System.Security;
9using System.Threading;
10using System.Threading.Tasks;
11using WGetNET.Builder;
14using WGetNET.Helper;
15using WGetNET.Models;
16using WGetNET.Parser;
17
18namespace WGetNET
19{
23 public class WinGet
24 {
25 private ProcessManager _processManager;
26 private string _wingetExePath;
27 private DateTime _wingetExeModificationDate;
28 private string _versionString;
29 private Version _version;
30 private bool _isPreview;
31
32 private readonly bool _administratorPrivileges;
33
40 public bool IsInstalled
41 {
42 get
43 {
44 // Check if the winget executable still exist to ensure a correct result,
45 // even if winget gets removed while the application is running.
46 if (File.Exists(_wingetExePath))
47 {
48 return true;
49 }
50 else
51 {
52 // Re-query installation and return the result to allow instalation of winget while the application is running.
53 return QueryInstallation();
54 }
55 }
56 }
57
64 public bool IsPreview
65 {
66 get
67 {
68 // Check if winget got modefied or removed while the application is running.
69 if (_wingetExeModificationDate != GetLastModificationData())
70 {
71 // Re-query installation if a change was detected.
72 QueryInstallation();
73 }
74
75 return _isPreview;
76 }
77 }
78
85 public string VersionString
86 {
87 get
88 {
89 // Check if winget got modefied or removed while the application is running.
90 if (_wingetExeModificationDate != GetLastModificationData())
91 {
92 // Re-query installation if a change was detected.
93 QueryInstallation();
94 }
95
96 return _versionString;
97 }
98 }
99
107 {
108 get
109 {
110 // Check if winget got modefied or removed while the application is running.
111 if (_wingetExeModificationDate != GetLastModificationData())
112 {
113 // Re-query installation if a change was detected.
114 QueryInstallation();
115 }
116
117 return _version;
118 }
119 }
120
124 public WinGet()
125 {
126 // Check if the current process has administrator privileges
127 _administratorPrivileges = SystemHelper.CheckAdministratorPrivileges();
128
129 // Set inital values
130 _processManager = new ProcessManager("winget");
131 _wingetExePath = string.Empty;
132 _wingetExeModificationDate = DateTime.MinValue;
133 _versionString = string.Empty;
134 _version = new Version(0, 0);
135
136 QueryInstallation();
137 }
138
139 //---Settings Export---------------------------------------------------------------------------
149 public string ExportSettings()
150 {
151 ProcessResult result = Execute(WinGetArguments.SettingsExport());
152
153 return ProcessOutputReader.ExportOutputToString(result);
154 }
155
169 public async Task<string> ExportSettingsAsync(CancellationToken cancellationToken = default)
170 {
171 ProcessResult result = await ExecuteAsync(WinGetArguments.SettingsExport(), false, cancellationToken);
172
173 return ProcessOutputReader.ExportOutputToString(result);
174 }
175
214 public void ExportSettingsToFile(string file)
215 {
216 ArgsHelper.ThrowIfStringIsNullOrWhiteSpace(file, "file");
217 ArgsHelper.ThrowIfPathIsInvalid(file);
218
219 ProcessResult result = Execute(WinGetArguments.SettingsExport());
220
221 FileHelper.WriteTextToFile(file, ProcessOutputReader.ExportOutputToString(result));
222 }
223
265 public async Task ExportSettingsToFileAsync(string file, CancellationToken cancellationToken = default)
266 {
267 ArgsHelper.ThrowIfStringIsNullOrWhiteSpace(file, "file");
268 ArgsHelper.ThrowIfPathIsInvalid(file);
269
270 ProcessResult result = await ExecuteAsync(WinGetArguments.SettingsExport(), false, cancellationToken);
271
272 await FileHelper.WriteTextToFileAsync(file, ProcessOutputReader.ExportOutputToString(result), cancellationToken);
273 }
274 //---------------------------------------------------------------------------------------------
275
276 //---Admin Settings----------------------------------------------------------------------------
286 public List<WinGetAdminSetting> GetAdminSettings()
287 {
288 List<WinGetAdminSetting> adminSettings = new();
289
290 string settingsJson = ExportSettings();
291
292 SettingsModel settings = JsonHelper.StringToObject<SettingsModel>(settingsJson);
293 if (settings == null)
294 {
295 return adminSettings;
296 }
297
298 WinGetAdminSettingBuilder builder = new();
299 foreach (KeyValuePair<string, bool> entry in settings.AdminSettings)
300 {
301 builder.Clear();
302
303 builder.AddEntryName(entry.Key);
304 builder.AddStatus(entry.Value);
305
306 WinGetAdminSetting? adminSetting = builder.GetInstance();
307 if (adminSetting != null)
308 {
309 adminSettings.Add(adminSetting);
310 }
311 }
312
313 return adminSettings;
314 }
315
329 public async Task<List<WinGetAdminSetting>> GetAdminSettingsAsync(CancellationToken cancellationToken = default)
330 {
331 List<WinGetAdminSetting> adminSettings = new();
332
333 string settingsJson = await ExportSettingsAsync(cancellationToken);
334
335#if NETCOREAPP3_1_OR_GREATER
336 SettingsModel settings = await JsonHelper.StringToObjectAsync<SettingsModel>(settingsJson, cancellationToken);
337#elif NETSTANDARD2_0
338 SettingsModel settings = JsonHelper.StringToObject<SettingsModel>(settingsJson);
339#endif
340 if (settings == null)
341 {
342 return adminSettings;
343 }
344
345 WinGetAdminSettingBuilder builder = new();
346 foreach (KeyValuePair<string, bool> entry in settings.AdminSettings)
347 {
348 if (cancellationToken.IsCancellationRequested)
349 {
350 return adminSettings;
351 }
352
353 builder.Clear();
354
355 builder.AddEntryName(entry.Key);
356 builder.AddStatus(entry.Value);
357
358 WinGetAdminSetting? adminSetting = builder.GetInstance();
359 if (adminSetting != null)
360 {
361 adminSettings.Add(adminSetting);
362 }
363 }
364
365 return adminSettings;
366 }
367
389 public bool EnableAdminSetting(string settingName)
390 {
391 ArgsHelper.ThrowIfStringIsNullOrWhiteSpace(settingName, "settingName");
392
393 ProcessResult result = Execute(WinGetArguments.Settings().Enable(settingName), true);
394
395 return result.Success;
396 }
397
420 {
421 ArgsHelper.ThrowIfObjectIsNull(setting, "setting");
422
423 return EnableAdminSetting(setting.EntryName);
424 }
425
451 public async Task<bool> EnableAdminSettingAsync(string settingName, CancellationToken cancellationToken = default)
452 {
453 ArgsHelper.ThrowIfStringIsNullOrWhiteSpace(settingName, "settingName");
454
455 ProcessResult result = await ExecuteAsync(WinGetArguments.Settings().Enable(settingName), true, cancellationToken);
456
457 return result.Success;
458 }
459
485 public async Task<bool> EnableAdminSettingAsync(WinGetAdminSetting setting, CancellationToken cancellationToken = default)
486 {
487 ArgsHelper.ThrowIfObjectIsNull(setting, "setting");
488
489 return await EnableAdminSettingAsync(setting.EntryName, cancellationToken);
490 }
491
513 public bool DisableAdminSetting(string settingName)
514 {
515 ArgsHelper.ThrowIfStringIsNullOrWhiteSpace(settingName, "settingName");
516
517 ProcessResult result = Execute(WinGetArguments.Settings().Disable(settingName), true);
518
519 return result.Success;
520 }
521
544 {
545 ArgsHelper.ThrowIfObjectIsNull(setting, "setting");
546
547 return DisableAdminSetting(setting.EntryName);
548 }
549
575 public async Task<bool> DisableAdminSettingAsync(string settingName, CancellationToken cancellationToken = default)
576 {
577 ArgsHelper.ThrowIfStringIsNullOrWhiteSpace(settingName, "settingName");
578
579 ProcessResult result = await ExecuteAsync(WinGetArguments.Settings().Disable(settingName), true, cancellationToken);
580
581 return result.Success;
582 }
583
609 public async Task<bool> DisableAdminSettingAsync(WinGetAdminSetting setting, CancellationToken cancellationToken = default)
610 {
611 ArgsHelper.ThrowIfObjectIsNull(setting, "setting");
612
613 return await DisableAdminSettingAsync(setting.EntryName, cancellationToken);
614 }
615 //---------------------------------------------------------------------------------------------
616
617 //---Info--------------------------------------------------------------------------------------
628 {
629 ProcessResult result = Execute(WinGetArguments.WinGet().Info());
630
631 InfoActionVersionId actionVersionId = InfoActionVersionId.VersionRange1;
632 if (CheckWinGetVersion(new Version(1, 4, 3531), new Version(1, 5, 101)))
633 {
634 actionVersionId = InfoActionVersionId.VersionRange2;
635 }
636 else if (CheckWinGetVersion(new Version(1, 5, 441), new Version(1, 5, 441)))
637 {
638 actionVersionId = InfoActionVersionId.VersionRange3;
639 }
640 else if (CheckWinGetVersion(new Version(1, 5, 1081)))
641 {
642 actionVersionId = InfoActionVersionId.VersionRange4;
643 }
644
645 return ProcessOutputReader.ToWingetInfo(result.Output, actionVersionId);
646 }
647
661 public async Task<WinGetInfo> GetInfoAsync(CancellationToken cancellationToken = default)
662 {
663 ProcessResult result = await ExecuteAsync(WinGetArguments.WinGet().Info(), false, cancellationToken);
664
665 // Check the version range the action should be performed for
666 InfoActionVersionId actionVersionId = InfoActionVersionId.VersionRange1;
667 if (CheckWinGetVersion(new Version(1, 4, 3531), new Version(1, 5, 101)))
668 {
669 actionVersionId = InfoActionVersionId.VersionRange2;
670 }
671 else if (CheckWinGetVersion(new Version(1, 5, 441), new Version(1, 5, 441)))
672 {
673 actionVersionId = InfoActionVersionId.VersionRange3;
674 }
675 else if (CheckWinGetVersion(new Version(1, 5, 1081)))
676 {
677 actionVersionId = InfoActionVersionId.VersionRange4;
678 }
679
680 // Return empty data if the task was canceled
681 if (cancellationToken.IsCancellationRequested)
682 {
683 return WinGetInfo.Empty;
684 }
685
686 return ProcessOutputReader.ToWingetInfo(result.Output, actionVersionId);
687 }
688 //---------------------------------------------------------------------------------------------
689
690 //---Custom execute----------------------------------------------------------------------------
707 {
708 ArgsHelper.ThrowIfObjectIsNull(args, "args");
709
710 ThrowIfNotInstalled();
711
712 WinGetResult result = new(Execute(args), args);
713
714 return result;
715 }
716
735 public WinGetResult ExecuteCustom(string args)
736 {
737 ArgsHelper.ThrowIfStringIsNullOrWhiteSpace(args, "args");
738
739 ThrowIfNotInstalled();
740
742
743 WinGetResult result = new(Execute(argsObj), argsObj);
744
745 return result;
746 }
747
766 public async Task<WinGetResult> ExecuteCustomAsync(WinGetArguments args, CancellationToken cancellationToken = default)
767 {
768 ArgsHelper.ThrowIfObjectIsNull(args, "args");
769
770 ThrowIfNotInstalled();
771
772 WinGetResult result = new(await ExecuteAsync(args, false, cancellationToken), args);
773
774 return result;
775 }
776
798 public async Task<WinGetResult> ExecuteCustomAsync(string args, CancellationToken cancellationToken = default)
799 {
800 ArgsHelper.ThrowIfStringIsNullOrWhiteSpace(args, "args");
801
802 ThrowIfNotInstalled();
803
805
806 WinGetResult result = new(await ExecuteAsync(argsObj, false, cancellationToken), argsObj);
807
808 return result;
809 }
810 //---------------------------------------------------------------------------------------------
811
812 //---Protected Functions-----------------------------------------------------------------------
813 // \cond PRIVATE
825 private protected bool CheckWinGetVersion(Version minVersion, Version? maxVersion = null)
826 {
827 Version winGetVersion = Version;
828 if ((winGetVersion.Major >= minVersion.Major && winGetVersion.Minor >= minVersion.Minor &&
829 ((winGetVersion.Minor != minVersion.Minor) || (winGetVersion.Minor == minVersion.Minor && winGetVersion.Build >= minVersion.Build))) &&
830 ((maxVersion == null) || (winGetVersion.Major <= maxVersion.Major && winGetVersion.Minor <= maxVersion.Minor &&
831 ((winGetVersion.Minor != maxVersion.Minor) || (winGetVersion.Minor == maxVersion.Minor && winGetVersion.Build <= maxVersion.Build)))))
832 {
833 return true;
834 }
835 return false;
836 }
837
857 private protected ProcessResult Execute(WinGetArguments args, bool needsAdminRights = false)
858 {
859 ThrowIfNotInstalled();
860
861 if (needsAdminRights)
862 {
863 ThrowIfNotAdmin();
864 }
865
866 return _processManager.ExecuteWingetProcess(args.Arguments);
867 }
868
892 private protected async Task<ProcessResult> ExecuteAsync(WinGetArguments args, bool needsAdminRights = false, CancellationToken cancellationToken = default)
893 {
894 ThrowIfNotInstalled();
895
896 if (needsAdminRights)
897 {
898 ThrowIfNotAdmin();
899 }
900
901 return await _processManager.ExecuteWingetProcessAsync(args.Arguments, cancellationToken);
902 }
903 // \endcond
904 //---------------------------------------------------------------------------------------------
905
906 //---Other-------------------------------------------------------------------------------------
913 private void ThrowIfNotInstalled()
914 {
915 if (!IsInstalled)
916 {
917 throw new WinGetNotInstalledException();
918 }
919 }
920
927 private void ThrowIfNotAdmin()
928 {
929 if (!_administratorPrivileges)
930 {
931 throw new SecurityException("Administrator privileges are missing.");
932 }
933 }
934
941 private string CheckWinGetVersion()
942 {
943 if (!IsInstalled)
944 {
945 return string.Empty;
946 }
947
948 ProcessResult result = Execute(WinGetArguments.WinGet().Version());
949
950 for (int i = 0; i < result.Output.Length; i++)
951 {
952#if NETCOREAPP3_1_OR_GREATER
953 if (result.Output[i].StartsWith('v') && result.Output[i].Length >= 2)
954 {
955 // Return output without the 'v' at the start.
956 return result.Output[i].Trim()[1..];
957 }
958#elif NETSTANDARD2_0
959 if (result.Output[i].StartsWith("v") && result.Output[i].Length >= 2)
960 {
961 // Return output without the 'v' at the start.
962 return result.Output[i].Trim().Substring(1);
963 }
964#endif
965 }
966
967 return string.Empty;
968 }
969
976 private DateTime GetLastModificationData()
977 {
978 if (string.IsNullOrWhiteSpace(_wingetExePath) || !File.Exists(_wingetExePath))
979 {
980 return DateTime.MinValue;
981 }
982
983 return File.GetLastWriteTimeUtc(_wingetExePath);
984 }
985
992 private bool QueryInstallation()
993 {
994 bool isInstalled;
995
996 _wingetExePath = SystemHelper.CheckWingetInstallation();
997
998 if (string.IsNullOrWhiteSpace(_wingetExePath))
999 {
1000 isInstalled = false;
1001 _processManager = new ProcessManager("winget");
1002 }
1003 else
1004 {
1005 isInstalled = true;
1006 _processManager = new ProcessManager(_wingetExePath);
1007 }
1008
1009 _wingetExeModificationDate = GetLastModificationData();
1010
1011 if (isInstalled)
1012 {
1013 _versionString = CheckWinGetVersion();
1014 }
1015 else
1016 {
1017 _versionString = string.Empty;
1018 }
1019
1020 _version = VersionParser.Parse(_versionString);
1021
1022 _isPreview = VersionParser.CheckPreviewStatus(_versionString);
1023
1024 return isInstalled;
1025 }
1026 //---------------------------------------------------------------------------------------------
1027 }
1028}
string EntryName
Gets the name of the info entry.
The WGetNET.WinGet class offers informations about the installed winget version.
Definition WinGet.cs:24
async Task< bool > DisableAdminSettingAsync(string settingName, CancellationToken cancellationToken=default)
Asynchronously disables the provided admin setting (Needs administrator rights).
Definition WinGet.cs:575
bool IsPreview
Gets if the version of winget is a preview version.
Definition WinGet.cs:65
WinGet()
Initializes a new instance of the WGetNET.WinGet class.
Definition WinGet.cs:124
bool IsInstalled
Gets if winget is installed on the system.
Definition WinGet.cs:41
async Task< WinGetResult > ExecuteCustomAsync(WinGetArguments args, CancellationToken cancellationToken=default)
Asynchronously exectutes WinGet with the provided arguments.
Definition WinGet.cs:766
async Task< List< WinGetAdminSetting > > GetAdminSettingsAsync(CancellationToken cancellationToken=default)
Asynchronously gets all winget admin settings.
Definition WinGet.cs:329
Version Version
Gets the version number of the winget installation.
Definition WinGet.cs:107
WinGetResult ExecuteCustom(WinGetArguments args)
Exectutes WinGet with the provided arguments.
Definition WinGet.cs:706
async Task< string > ExportSettingsAsync(CancellationToken cancellationToken=default)
Asynchronous exports the WinGet settings to a json string.
Definition WinGet.cs:169
async Task ExportSettingsToFileAsync(string file, CancellationToken cancellationToken=default)
Asynchronous exports the WinGet settings to a json and writes them to the given file.
Definition WinGet.cs:265
List< WinGetAdminSetting > GetAdminSettings()
Gets all winget admin settings.
Definition WinGet.cs:286
bool EnableAdminSetting(WinGetAdminSetting setting)
Enables the provided admin setting (Needs administrator rights).
Definition WinGet.cs:419
async Task< bool > EnableAdminSettingAsync(WinGetAdminSetting setting, CancellationToken cancellationToken=default)
Asynchronously enables the provided admin setting (Needs administrator rights).
Definition WinGet.cs:485
string ExportSettings()
Exports the WinGet settings to a json string.
Definition WinGet.cs:149
async Task< bool > EnableAdminSettingAsync(string settingName, CancellationToken cancellationToken=default)
Asynchronously enables the provided admin setting (Needs administrator rights).
Definition WinGet.cs:451
string VersionString
Gets the version number of the winget installation.
Definition WinGet.cs:86
bool DisableAdminSetting(string settingName)
Disables the provided admin setting (Needs administrator rights).
Definition WinGet.cs:513
WinGetInfo GetInfo()
Gets all WinGet related data provided by the WinGet info action.
Definition WinGet.cs:627
bool EnableAdminSetting(string settingName)
Enables the provided admin setting (Needs administrator rights).
Definition WinGet.cs:389
async Task< WinGetInfo > GetInfoAsync(CancellationToken cancellationToken=default)
Asynchronous gets all WinGet related data provided by the WinGet info action.
Definition WinGet.cs:661
bool DisableAdminSetting(WinGetAdminSetting setting)
Disables the provided admin setting (Needs administrator rights).
Definition WinGet.cs:543
void ExportSettingsToFile(string file)
Exports the WinGet settings to a json and writes them to the given file.
Definition WinGet.cs:214
async Task< bool > DisableAdminSettingAsync(WinGetAdminSetting setting, CancellationToken cancellationToken=default)
Asynchronously disables the provided admin setting (Needs administrator rights).
Definition WinGet.cs:609
WinGetResult ExecuteCustom(string args)
Exectutes WinGet with the provided arguments.
Definition WinGet.cs:735
async Task< WinGetResult > ExecuteCustomAsync(string args, CancellationToken cancellationToken=default)
Asynchronously exectutes WinGet with the provided arguments.
Definition WinGet.cs:798
Represents a winget admin settings entry.
Represents a winget arguments string for different winget actions.
static WinGetArguments WinGet()
Creates a new winget arguments object with no base cmd. Used for direct callin of the winget cmd with...
WinGetArguments Disable(string query)
Adds a disable action to the arguments.
static WinGetArguments SettingsExport()
Creates a new winget arguments object with "settings export" as the base cmd.
string Arguments
Gets the generated arguments.
static WinGetArguments Settings()
Creates a new winget arguments object with "settings" as the base cmd.
static WinGetArguments CustomCmd(string cmd)
Creates a new winget arguments object with a custom base cmd.
WinGetArguments Info()
Adds the '–info' flag to the arguments.
WinGetArguments Enable(string query)
Adds a enable action to the arguments.
WinGetArguments Version(string version)
Adds a version query to the arguments.
Represents winget related information.
Definition WinGetInfo.cs:15
Represents a winget execution result.
Exception that gets thrown if winget is not installed.