Home > database >  VB .NET - How to check if 'File and Printer Sharing' is enabled
VB .NET - How to check if 'File and Printer Sharing' is enabled

Time:06-24

I have written a VB .Net front-end to the office SQL server. I want to expand this so users can access the server via a VPN. When testing the process, I can only see the SQL server via the VPN if I also have 'File and Printer Sharing' enabled on each client PC, so I want some code to check that both the VPN and the sharing are enabled before trying to access the server. I have the following three lines which checks that the VPN is running:

    Dim myInterfaceList As NetworkInterface() = NetworkInterface.GetAllNetworkInterfaces
    Dim myVPNRunning As Boolean = myInterfaceList.AsEnumerable().Any(Function(x) x.Name = "MyTestVPN")
    If myVPNRunning Then chkProgress3.Checked = True

but I can't find a way (in VB .NET) to check if the client PC has 'File and Printer Sharing' enabled. I have found this article 1 which discusses using Powershell to check, but I don't know how to translate this into VB .Net code (or even if this is the correct / best way). The office network is not a Domain, so I can't enable sharing through Group Policy.

Has anyone else tackled this? Thanks, Tim

CodePudding user response:

The following shows how to check if File and Printer sharing is enabled using PowerShell in VB.NET.

Download/install NuGet package for PowerShell

  • Microsoft.PowerShell.5.1.ReferenceAssemblies (.NET Framework)
  • Microsoft.PowerShell.SDK (.NET 6)

See this post for more information.


Add the following Imports statements:

  • Imports System.Management.Automation

IsFileAndPrinterSharingEnabled:

Private Function IsFileAndPrinterSharingEnabled() As Boolean
    Using ps As PowerShell = PowerShell.Create()
        Dim result As String = ps.AddScript("Get-NetAdapterBinding | ? {$_.DisplayName -eq 'File and Printer Sharing for Microsoft Networks' -and $_.Name -eq 'ethernet'} | Select -ExpandProperty Enabled").Invoke()(0).ToString()
        'Dim result As String = ps.AddScript("Get-NetAdapterBinding | ? {$_.DisplayName -eq 'File and Printer Sharing for Microsoft Networks' -and $_.Name -eq 'ethernet'} | ForEach-Object {$_.Enabled}").Invoke()(0).ToString()

        If result = "True" Then
            Return True
        End If
    End Using

    Return False
End Function

Resources:

Other Resources

  • Related