Open INI file and place content in different textboxes - vb.net

I am creating a program in VB.net that opens a .INI file and reads the content. I wrote the following code:
Private Sub OpenINIButton_Click(sender As Object, e As EventArgs) Handles OpenINIButton.Click
Dim OpenDLG As New OpenFileDialog
Dim FileLocation = OpenDLG.FileName.ToString()
OpenDLG.Filter = "INI File (*.ini)|*.ini"
OpenDLG.Title = "Open INI File"
OpenDLG.InitialDirectory = "C:\"
OpenDLG.RestoreDirectory = True
DialogResult = OpenDLG.ShowDialog
If DialogResult = Windows.Forms.DialogResult.OK Then
TextBox1.Text = ReadIni(FileLocation, INIkey, INIvalue, "")
ElseIf DialogResult = Windows.Forms.DialogResult.Cancel Then
End If
End Sub
The open file dialog opens and I can open a INI file but the value of INIkey is not placed in TextBox1.
Any idea how I can fix this?

You initialize the path beore the user has selected it:
Dim FileLocation = OpenDLG.FileName.ToString()
Do that after ShowDialog, so here is the correct place:
If DialogResult = Windows.Forms.DialogResult.OK Then
Dim FileLocation = OpenDLG.FileName.ToString()
TextBox1.Text = ReadIni(FileLocation, INIkey, INIvalue, "")
ElseIf DialogResult = Windows.Forms.DialogResult.Cancel Then
End If
But why don't you notice an exception? I assume that you have an empty catch block where you try to open the file in ReadIni. That's a bad habit to kick anyway.
Note that the FileLocation variable in your code references the String OpenDLG.FileName at the time you assign it, there is no permanent connection between both. So if it changes later the variable references still the old string.

The best way to do this would be to make an iniParse module like below and just use the function as shown:
Module iniParse
Public readwrtie As Integer
Public settingValueReturn As New System.Text.StringBuilder(255)
Private Declare Auto Function WritePrivateProfileString Lib "Kernel32" _
(ByVal IpApplication As String, ByVal Ipkeyname As String, _
ByVal IpString As String, ByVal IpFileName As String) As Integer
Private Declare Auto Function GetPrivateProfileString Lib "Kernel32" _
(ByVal IpApplicationName As String, ByVal IpKeyName As String, _
ByVal IpDefault As String, ByVal IPReturnedString As System.Text.StringBuilder, _
ByVal nsize As Integer, ByVal IpFileName As String) As Integer
Public Sub WriteINIFile(heading As String, setting As String, settingvalue As String, path As String)
WritePrivateProfileString(heading, setting, settingvalue, path)
End Sub
Public Sub ReadIniFile(heading As String, setting As String, path As String)
GetPrivateProfileString(heading, setting, "", settingValueReturn, 100, path)
End Sub
End Module
Example:
Button1_click blah blah blah handles button1.click...
ReadIniFile("MAIN", "test", "C:\config.ini")
'this would read the following ini file:
'[MAIN]
'test=hi
'to get that 'hi' value you would use this code:
textbox1.text = settingReturnValue.tostring '(settingValueReturn Will always be the value of the setting entered in the function args)
'to write ini file:
Button1_click blah blah blah handles button1.click...
WriteIniFile("MAIN", "test2", "hi2", "C:\config.ini")
'this would write the following to the ini # C:\config.ini file:
'[MAIN]
'test2=hi2
I hope this helps your needs!

Related

VB.NET Display file icons from Network Paths with calling Shell

I have this program that shows files with its icons using a ListView and it works a little bit fine but there's a problem, some files(.exe, .docx etc...) don't show their right icon like this. how do I fix that?
This is how I call the Shell:
' declare the Win32 API function SHGetFileInfo'
Public Declare Auto Function SHGetFileInfo Lib "shell32.dll" (ByVal pszPath As String, ByVal dwFileAttributes As Integer, ByRef psfi As SHFILEINFO, ByVal cbFileInfo As Integer, ByVal uFlags As Integer) As IntPtr
' declare some constants that SHGetFileInfo requires'
Public Const SHGFI_ICON As Integer = &H100
Public Const SHGFI_SMALLICON As Integer = &H1
' define the SHFILEINFO structure'
Structure SHFILEINFO
Public hIcon As IntPtr
Public iIcon As Integer
Public dwAttributes As Integer
<Runtime.InteropServices.MarshalAs(Runtime.InteropServices.UnmanagedType.ByValTStr, SizeConst:=260)> _
Public szDisplayName As String
<Runtime.InteropServices.MarshalAs(Runtime.InteropServices.UnmanagedType.ByValTStr, SizeConst:=80)> _
Public szTypeName As String
End Structure
Function RetrieveShellIcon(ByVal argPath As String) As Image
Dim mShellFileInfo As SHFILEINFO
Dim mSmallImage As IntPtr
Dim mIcon As System.Drawing.Icon
Dim mCompositeImage As Image
mShellFileInfo = New SHFILEINFO
mShellFileInfo.szDisplayName = New String(Chr(0), 260)
mShellFileInfo.szTypeName = New String(Chr(0), 80)
mSmallImage = SHGetFileInfo(argPath, 0, mShellFileInfo, System.Runtime.InteropServices.Marshal.SizeOf(mShellFileInfo), SHGFI_ICON Or SHGFI_SMALLICON)
' create the icon from the icon handle'
Try
mIcon = System.Drawing.Icon.FromHandle(mShellFileInfo.hIcon)
mCompositeImage = mIcon.ToBitmap
Catch ex As Exception
' create a blank black bitmap to return'
mCompositeImage = New Bitmap(16, 16)
End Try
' return the composited image'
Return mCompositeImage
End Function
Function GetIcon(ByVal argFilePath As String) As Image
Dim mFileExtension As String = System.IO.Path.GetExtension(argFilePath)
' add the image if it doesn't exist'
If cIcons.ContainsKey(mFileExtension) = False Then
cIcons.Add(mFileExtension, RetrieveShellIcon(argFilePath))
End If
' return the image'
Return cIcons(mFileExtension)
End Function
and this is how I show file icons in my `ListView.
Sub lv1items()
Dim lvi As ListViewItem
Dim di As New DirectoryInfo(Form2.TextBox1.Text)
Dim exts As New List(Of String)
ImageList1.Images.Clear()
If di.Exists = False Then
MessageBox.Show("Source path is not found", "Directory Not Found", MessageBoxButtons.OK, MessageBoxIcon.Error)
Else
For Each fi As FileInfo In di.EnumerateFiles("*.*")
lvi = New ListViewItem
lvi.Text = fi.Name
lvi.SubItems.Add(((fi.Length / 1024)).ToString("0.00"))
lvi.SubItems.Add(fi.CreationTime.ToShortDateString)
If exts.Contains(fi.Extension) = False Then
Dim mShellIconManager As New Form1
For Each mFilePath As String In My.Computer.FileSystem.GetFiles(Form2.TextBox1.Text)
ImageList1.Images.Add(fi.Extension, GetIcon(mFilePath))
exts.Add(fi.Extension)
Next
End If
lvi.ImageKey = fi.Extension
ListView1.Items.Add(lvi)
Next
End If
End Sub
That appears to be a weird limitation of the .net implication
its really just making a call to shell32.dll
You should call the function in shell32 directly
something like this should work
<DllImport("shell32.dll")>
Private Shared Function ExtractAssociatedIcon(hInst As IntPtr, lpIconPath As StringBuilder, ByRef lpiIcon As UShort) As IntPtr
End Function
_
Dim handle As IntPtr = SafeNativeMethods.ExtractAssociatedIcon(New HandleRef(Nothing, IntPtr.Zero), iconPath, index)
If handle <> IntPtr.Zero Then
Return Icon.FromHandle(handle)
End If
The syntax might not be exactly correct, also there is a good blog post about how to pull that information from the registry (which won't always give you the correct answer, but its faster)
Building a Better ExtractIcon (he uses the SHGetFileInfo API in shell32.dll if that blog ever dies it will give people a place to start looking)

VB.NET: Can't load audio from resources

I'm trying to add multiple sounds on an application using a Public function... When I use the absolute path for my sounds everything works perfectly, but when I'm trying to load them from Resources I don't get any sound output.. Any ideas what's wrong?
Public Class Form1
Public Declare Function mciSendString Lib "winmm.dll" Alias "mciSendStringA" (ByVal lpstrCommand As String, ByVal lpstrReturnString As String, ByVal uReturnLength As Integer, ByVal hwndCallback As Integer) As Integer
Dim musicAlias As String = "myAudio"
'Dim musicPath As String = "C:\Users\Teo\Documents\Visual Studio 2015\Projects\test\test\Resources\sound.mp3"
'Dim musicPath As String = "Resources\sound.mp3"
'Dim musicPath As String = My.Resources.ResourceManager.GetObject("sound.mp3")
Dim musicPath2 As String = "C:\Users\Teo\Desktop\sound.mp3"
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
mciSendString("Open " & musicPath & " alias " & musicAlias, CStr(0), 0, 0)
mciSendString("play " & musicAlias, CStr(0), 0, 0)
End Sub
End Class
The last one works perfectly, I tried every one of the above... The three comments above are different ways I tried to make it work, but all failed...
You can load the file from resources and cache them locally and play them.
Open Resources.resx file under My Project. Then add your file for example YourFileName.mp3 to the resources by choosing Add Existing File... then when you want to play the file, use this code:
Dim file As String = System.IO.Path.Combine(Application.StartupPath, "YourFileName.mp3")
If (Not System.IO.File.Exists(file)) Then
System.IO.File.WriteAllBytes(file, My.Resources.YourFileName)
End If
'Now the file exists locally
'Play the file here
I know this has an answer marked correct, but once you have a sound file in your Resources, it's much easier this way:
My.Computer.Audio.Play(My.Resources.MyCoolSound, AudioPlayMode.Background)
No reason to use an API call.

Replicate Windows Unhide folders and files function

I'm re-visiting a tool that I wrote in VB.Net for my helpdesk team a while back and want to add a couple of checkboxes to replicate the same function that Windows uses to show hidden files and folders / re-hide, as well as protected operating system files.
I know I can do this by editing a registry entry and restarting explorer.exe, but that closes all open Explorer Windows and I don't want that.
Does anyone know how Windows is able to do this by a simple click of a checkbox and how I may be able to code it in VB.net?
Any input on this is greatly appreciated in advance.
EDIT: So it looks like I have found a refresh method that works to refresh Windows Explorer / File Explorer which can be applied to Drarig's answer below but I am having trouble converting it to VB.net as the original example is in C#.
'Original at http://stackoverflow.com/questions/2488727/refresh-windows-explorer-in-win7
Private Sub refreshExplorer(ByVal explorerType As String)
Dim CLSID_ShellApplication As Guid = Guid.Parse("13709620-C279-11CE-A49E-444553540000")
Dim shellApplicationType As Type = Type.GetTypeFromCLSID(CLSID_ShellApplication, True)
Dim shellApplication As Object = Activator.CreateInstance(shellApplicationType)
Dim windows As Object = shellApplicationType.InvokeMember("Windows", Reflection.BindingFlags.InvokeMethod, Nothing, shellApplication, New Object() {})
Dim windowsType As Type = windows.GetType()
Dim count As Object = windowsType.InvokeMember("Count", Reflection.BindingFlags.GetProperty, Nothing, windows, Nothing)
For i As Integer = 0 To CType(count, Integer)
Dim item As Object = windowsType.InvokeMember("Item", Reflection.BindingFlags.InvokeMethod, Nothing, windows, New Object() {i})
Dim itemType As Type = item.GetType()
'Only fresh Windows explorer Windows
Dim itemName As String = CType(itemType.InvokeMember("Name", Reflection.BindingFlags.GetProperty, Nothing, item, Nothing), String)
If itemName = explorerType Then
itemType.InvokeMember("Refresh", Reflection.BindingFlags.InvokeMethod, Nothing, item, Nothing)
End If
Next
End Sub
I am getting an exception Object reference not set to an instance of an object when I set itemType as Type = item.GetType() above. I can't figure out which object isn't being created. When I step through the code it looks like windowsType contains an object for windows. Does anyone have any idea on this? Once this is worked out I can then apply it to Drarig's solution below.
Alright I wish I could have got this to you sooner, but busy lately at work. I took a little time today to figure this out as I love digging into something I have not done before. This is the whole class from a new project; didn't have time to wrap it up in a separate class. I am sure this will get you what you need. It was a little harder than I thought as getting the correct handle and then send the command, but I got it. I hope you find it useful.
P.S. Some of the things you can leave out, specifically the boolean used for loading, this was so I can pull the current value back on load and either check/uncheck the CheckBox.
Note: This is tried and tested on Windows 7, 8 and 10
Imports Microsoft.Win32
Imports System.Reflection
Imports System.Runtime.InteropServices
Public Class Form1
<Flags()> _
Public Enum KeyboardFlag As UInteger
KEYBOARDF_5 = &H74
End Enum
<DllImport("user32.dll", SetLastError:=True, CharSet:=CharSet.Auto)> _
Private Shared Function GetWindow(ByVal hl As Long, ByVal vm As Long) As IntPtr
End Function
<DllImport("user32.dll", SetLastError:=True, CharSet:=CharSet.Auto)> _
Private Shared Function PostMessage(ByVal hWnd As IntPtr, ByVal Msg As UInteger, ByVal wParam As IntPtr, ByVal lParam As IntPtr) As Boolean
End Function
<DllImport("user32.dll", SetLastError:=True, CharSet:=CharSet.Auto)> _
Private Shared Function FindWindow(ByVal lpClassName As String, ByVal lpWindowName As String) As IntPtr
End Function
Private blnLoading As Boolean = False
Private Sub CheckBox1_CheckedChanged(sender As Object, e As EventArgs) Handles CheckBox1.CheckedChanged
Form1.HideFilesExtension(Me.CheckBox1.Checked)
If Not blnLoading Then NotifyFileAssociationChanged()
RefreshExplorer()
End Sub
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim name As String = "Software\Microsoft\Windows\CurrentVersion\Explorer\Advanced"
Dim key As RegistryKey = Registry.CurrentUser.OpenSubKey(name, False)
blnLoading = True
Me.CheckBox1.Checked = CBool(key.GetValue("Hidden"))
key.Close()
blnLoading = False
End Sub
Private Shared Sub HideFilesExtension(ByVal Hide As Boolean)
Dim name As String = "Software\Microsoft\Windows\CurrentVersion\Explorer\Advanced"
Dim key As RegistryKey = Registry.CurrentUser.OpenSubKey(name, True)
key.SetValue("Hidden", If(Hide, 1, 0))
key.Close()
End Sub
Public Shared Sub RefreshExplorer()
Dim clsid As New Guid("13709620-C279-11CE-A49E-444553540000")
Dim typeFromCLSID As Type = Type.GetTypeFromCLSID(clsid, True)
Dim objectValue As Object = Activator.CreateInstance(typeFromCLSID)
Dim obj4 As Object = typeFromCLSID.InvokeMember("Windows", BindingFlags.InvokeMethod, Nothing, objectValue, New Object(0 - 1) {})
Dim type1 As Type = obj4.GetType
Dim obj2 As Object = type1.InvokeMember("Count", BindingFlags.GetProperty, Nothing, obj4, Nothing)
If (CInt(obj2) <> 0) Then
Dim num2 As Integer = (CInt(obj2) - 1)
Dim i As Integer = 0
Do While (i <= num2)
Dim obj5 As Object = type1.InvokeMember("Item", BindingFlags.InvokeMethod, Nothing, obj4, New Object() {i})
Dim type3 As Type = obj5.GetType
Dim str As String = CStr(type3.InvokeMember("Name", BindingFlags.GetProperty, Nothing, obj5, Nothing))
If (str = "File Explorer") Then
type3.InvokeMember("Refresh", BindingFlags.InvokeMethod, Nothing, obj5, Nothing)
End If
i += 1
Loop
End If
End Sub
Public Shared Sub NotifyFileAssociationChanged()
'Find the actual window...
Dim hwnd As IntPtr = FindWindow("Progman", "Program Manager")
'Get the window handle and refresh option...
Dim j = GetWindow(hwnd, 3)
'Finally post the message...
PostMessage(j, 256, KeyboardFlag.KEYBOARDF_5, 3)
End Sub
End Class
Here's a solution for everything excepting the refreshing of the explorer.
I've translated the code, but I'm unable to find how to refresh the explorer/desktop without restarting it.
Const keyName As String = "HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Explorer\Advanced"
Const Hidden As String = "Hidden"
Const SHidden As String = "ShowSuperHidden"
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim St As Integer = GetRegValue(Hidden)
If St = 2 Then
SetRegValue(Hidden, 1)
SetRegValue(SHidden, 1)
Else
SetRegValue(Hidden, 2)
SetRegValue(SHidden, 0)
End If
End Sub
Private Function GetRegValue(valueName As String) As Integer
Return CInt(My.Computer.Registry.GetValue(keyName, valueName, 0))
End Function
Private Sub SetRegValue(valueName As String, value As Integer)
My.Computer.Registry.SetValue(keyName, valueName, value, Microsoft.Win32.RegistryValueKind.DWord)
End Sub
I have a few ideas to refresh the desktop :
Send a key to a running process. I tried this (source) :
Dim pp As Process() = Process.GetProcessesByName("explorer")
If pp.Length > 0 Then
For Each p In pp
AppActivate(p.Id)
SendKeys.SendWait("{F5}")
Next
End If
Refresh using SHChangeNotify (source),
Refresh broadcasting a WM_SETTINGCHANGE message (source),
etc.
I think you'll be forced to manually refresh or restart the explorer.

VB.NET How to write text to a .ini file?

I'm creating a program that will help users create a certain config file for another program that usually has to be done by hand.
The programs config file reads it like; 'This_Setting = 0/1 (Off/On)'
So I want to make it so that if the user ticks say a checkbox on my program, it will write in the text file '1' and if it is unticked, it will write '0'.
Another way I thought about doing it was having a text box, the user ticks the boxes they want, and then click a button and then it would paste the config code in the text box so they could copy/paste it. I personally think this would be a better option, but I still have not the slightest clue how to do it.
Any help is appreciated!
If you just need to create a file, then File.WriteAllText is probably what you need. If it is a large file, you can use the StringBuilder class to build up the contents of the file, or if it is a small file, you can use simple string concatenation. After you have your string, you can use File.WriteAllText to write it to disk.
The traditional way is to use GetPrivateProfileString (or GetPrivateProfileSection) to retrieve INI settings, and WritePrivateProfileString (or WritePrivateProfileSection) to change them.
You can find the syntax at PInvoke
Here is the VB.NET code to write to INI file,
Imports System.IO
Imports System.Text
Imports System.Runtime.InteropServices
Public Class Form1
<DllImport("kernel32")>
Private Shared Function WritePrivateProfileString(ByVal lpSectionName As String, ByVal lpKeyName As String, ByVal lpString As String, ByVal lpFileName As String) As Long
End Function
Private Function SetIniValue(section As String, key As String, filename As String, Optional defaultValue As String = "") As String
Dim sb As New StringBuilder(500)
If WritePrivateProfileString(section, key, defaultValue, filename) > 0 Then
Return sb.ToString
Else
Return defaultValue
End If
End Function
Private Sub WriteToINI()
SetIniValue("default", "This_Setting", "C:\myconfigfile.ini", "1")
End Sub
End Class
Reference: http://vbnet.mvps.org/index.html?code/file/pprofilebasic.htm
This should be very easy. What you would want to do is use the following code.
FileOpen(1, "WHATEVER-THE-FILE-PATH-IS.ini", OpenMode.Output)
PrintLine(1, "WHATEVER-TEXT-YOU-WANT-TO-WRITE")
FileClose(1)
All you have to do is just change some things to make it suit your needs. First of all, on FileOpen() you want to change where it says "WHATEVER-THE-FILE-PATH-IS.ini" to your file path (make sure you have .ini on the end.)
The next thing you have to do to make this work is change where it says OpenMode.Output. You use OpenMode.Output to write to a text file, you use OpenMode.Input when you want to read from a text file (you would use that when you load the application) and you use OpenMode.Append to just add text on.
Now there are some things you need to look out for:
When you use OpenMode.Output it actually clears all the text from the text file first and then writes the text you want to write.
When you use OpenMode.Input you can't use PrintLine(1, "WHATEVER") as that is for writing to the text file not reading - so it will just crash. When using OpenMode.Input to read from the text file you have to use LineInput(1)
For Example:
Dim bool As Boolean
FileOpen(1, "WHATEVER", OpenMode.Input)
If LineInput(1) = "1" Then bool = True Else bool = False
FileClose(1)
This code will read the .ini file and if it says 1 in it then it will set the value to True and if it has 0 in it then it will set the value to False!
So here is the code after all going through all that!
To load the values:
Dim bool As Boolean
FileOpen(1, "WHATEVER.ini", OpenMode.Input)
If LineInput(1) = "1" Then bool = True Else bool = False
FileClose(1)
To save the values:
Dim bool As Boolean
FileOpen(1, "WHATEVER.ini", OpenMode.Input)
If bool = True Then PrintLine(1, "1") Else PrintLine(1, "0")
FileClose(1)
(don't forget you can add as many PrintLine(1, "") and LineInput(1) as you want)
A Class for reading and writing .INI files easily.
I didn't make these.
Instructions
Put this code into your project.
VB Code:
Class INIReadWrite
<DllImport("kernel32.dll", SetLastError:=True)> _
Private Shared Function GetPrivateProfileString(ByVal lpAppName As >String, ByVal lpKeyName As String, ByVal lpDefault As String, ByVal >lpReturnedString As StringBuilder, ByVal nSize As Integer, ByVal lpFileName >As String) As Integer
End Function
<DllImport("kernel32.dll", SetLastError:=True)> _
Private Shared Function WritePrivateProfileString(ByVal lpAppName As >String, ByVal lpKeyName As String, ByVal lpString As String, ByVal >lpFileName As String) As Boolean
End Function
Public Shared Function ReadINI(ByVal File As String, ByVal Section As >String, ByVal Key As String) As String
Dim sb As New StringBuilder(500)
GetPrivateProfileString(Section, Key, "", sb, sb.Capacity, File)
Return sb.ToString
End Function
Public Shared Sub WriteINI(ByVal File As String, ByVal Section As >String, ByVal Key As String, ByVal Value As String)
WritePrivateProfileString(Section, Key, Value, File)
End Sub
End Class
To read an .INI file
Code:
ReadINI(File, Section, Key)
To write to an .INI file
Code:
WriteINI(File, Section, Key, Value)

Getting file listings

I am wanting to retrieve all the files in some directories. Here is my original code:
Private Function Search(path As String, Recursive As Boolean) As Boolean
Dim dirInfo As New IO.DirectoryInfo(path)
Dim fileObject As FileSystemInfo
If Recursive = True Then
For Each fileObject In dirInfo.GetFileSystemInfos()
If fileObject.Attributes = FileAttributes.Directory Then
Search(fileObject.FullName, Recursive)
Else
lstFiles.Items.Add(fileObject.FullName)
End If
Next
Else
For Each fileObject In dirInfo.GetFileSystemInfos()
lstFiles.Items.Add(fileObject.FullName)
Next
End If
Return True
End Function
This code works well, yet it returns some directories and I am wanting to only return files.
I tried this code:
Private Sub Search(ByVal path As String, ByVal Recursive As Boolean)
if not Directory.Exists(path) then Exit Sub
Dim initDirInfo As New DirectoryInfo(path)
For Each oFileInfo In initDirInfo.GetFiles
lstfiles.items.add(oFileInfo.Name)
Next
If Recursive Then
For Each oDirInfo In initDirInfo.GetDirectories
Search(oDirInfo.FullName, True)
Next
End If
End Sub
However, i get the following error:
Access to the path 'C:\Users\Simon\AppData\Local\Application Data\' is denied.
Can someone help me with my original code, or help me access these directories with my new code?
thanks
EDIT:
I have added this module to get it working:
Imports System.Security.Principal
Module VistaSecurity
'Declare API
Private Declare Ansi Function SendMessage Lib "user32.dll" Alias "SendMessageA" (ByVal hwnd As Integer, ByVal wMsg As Integer, ByVal wParam As Integer, ByVal lParam As String) As Integer
Private Const BCM_FIRST As Int32 = &H1600
Private Const BCM_SETSHIELD As Int32 = (BCM_FIRST + &HC)
Public Function IsVistaOrHigher() As Boolean
Return Environment.OSVersion.Version.Major < 6
End Function
' Checks if the process is elevated
Public Function IsAdmin() As Boolean
Dim id As WindowsIdentity = WindowsIdentity.GetCurrent()
Dim p As WindowsPrincipal = New WindowsPrincipal(id)
Return p.IsInRole(WindowsBuiltInRole.Administrator)
End Function
' Add a shield icon to a button
Public Sub AddShieldToButton(ByRef b As Button)
b.FlatStyle = FlatStyle.System
SendMessage(b.Handle, BCM_SETSHIELD, 0, &HFFFFFFFF)
End Sub
' Restart the current process with administrator credentials
Public Sub RestartElevated()
Dim startInfo As ProcessStartInfo = New ProcessStartInfo()
startInfo.UseShellExecute = True
startInfo.WorkingDirectory = Environment.CurrentDirectory
startInfo.FileName = Application.ExecutablePath
startInfo.Verb = "runas"
Try
Dim p As Process = Process.Start(startInfo)
Catch ex As Exception
Return 'If cancelled, do nothing
End Try
Application.Exit()
End Sub
End Module
The access denied errors are occurring at Windows Libraries I think. I don't think there is any way to list the file in these libraries as they aren't actually folders.