Reputation: 53
I have a comboBox that sorts the List<(tuple)> by LastAccessTime, Basically Recently used but when Im extracting an Icon.ExtractAssociatedIcon() I know that It updates LastAccessTime and I cant suppress it. What I came up is to save the LastAccessTime into a DateTime originalLastAccessTime variable and then after I do my Icon.ExtractAssociatedIcon() I do File.SetLastAccessTime(originalLastAccessTime) and then add the originalLAT variable to the List of tuples so I can sort it later through Another ComboBox by Recently used. But I get UnauthorizedAccessException because some files directories need Privileges AKA: run as Admin. How can I make it work I dont mind if the user doesnt get all the Apps listed in the ComboBox and when he runs as Admin he gets them. I tried using Try-Catch statement but Ive heard its slow and im not satisfied if anyone can help how I can make it better or if there is a better way to sort by Recently Used or Extract the Icon from an .exe without updating LastAccessTime i would be really grateful.
using (RegistryKey? appKey = uninstallKey.OpenSubKey(subKeyNames[i]))
{
if (appKey != null)
{
string? displayNameValue = appKey.GetValue("DisplayName") as string;
string? displayInstallLocation = appKey.GetValue("InstallLocation") as string;
Icon? exeIcon = null;
if (!string.IsNullOrEmpty(displayInstallLocation) && !displayInstallLocation.Contains("WINDOWS") && !displayInstallLocation.Contains("Microsoft") && !displayInstallLocation.Contains("Atom") && !string.IsNullOrEmpty(displayNameValue) && Directory.Exists(displayInstallLocation)) //Arranged them based on which is more likely to fail first and has more paths to check(This way the condition check ends faster)
{
string[] getAllExeLocation = Directory.GetFiles(displayInstallLocation, "*.exe", SearchOption.AllDirectories);
for (int l = 0; l < getAllExeLocation.Length; l++)
{
FileInfo fileInfoLocation = new FileInfo(getAllExeLocation[l]);
DateTime originalLastAccessTime = fileInfoLocation.LastAccessTime; //Get the Original LastAccessTime before its updated
exeIcon = Icon.ExtractAssociatedIcon(fileInfoLocation.FullName);
exeIcon = ResizeIcon(exeIcon, 16, 16); // Adjust the size of the Icon so it fits the ComboBox
try
{
File.SetLastAccessTime(fileInfoLocation.FullName, originalLastAccessTime);//Set the Old LastAccessTime overwritting the new one but needs Privileges for some files
displayNameAndIcon.Add((displayNameValue, exeIcon, fileInfoLocation, originalLastAccessTime));
}
catch (UnauthorizedAccessException)
{
}
}
}
}
}
I know there is C++ Alternative by Rymond Chans Blog but it didnt work for me in C# tried ChatGPT and everything.
Upvotes: 0
Views: 25