简体   繁体   中英

convert code snippet to C#

VS 2008

I have this code snippet I found on a VB website.

But for some reason I am having trouble converting it to C#.

My.Computer.Network.IsAvailable

Many thanks,

using System.Net.NetworkInformation;

    internal class Program
    {
        private static void Main()
        {
            NetworkInterface.GetIsNetworkAvailable();
        }
    }

Yes, garethm is right, this class (Network) is from a VB.NET library - you need to reference the Microsoft.VisualBasic assembly if using in a C# project.

Microsoft.VisualBasic.Devices.Network n = new Microsoft.VisualBasic.Devices.Network();
if (n.IsAvailable)
{
    // do stuff
}

Works for me - my network is available :).

As far as how Network relates to NetworkInterface class, it depends on what you want to do next. For instance, Network has such nice stuff as NetworkAvailabilityChanged event, and UploadFile method. On the other hand, NetworkInterface can give you a bunch of specific technical info such as speed or whether it supports multicast.

BTW, there is nothing undocumented about using a class from Microsoft.VisualBasic namespace - it's the core idea behind .NET that you can use classes from assemblies regardless of the language they were written in.

What I generally do is write a small app, then load then project in Reflector and disassemble it.

but you can use this class: System.Net.NetworkInformation.NetworkChange.NetworkAddressChanged

This appears to work. It's probably very undocumented usage though:

        Microsoft.VisualBasic.Devices.Network net = new Microsoft.VisualBasic.Devices.Network();
        if (net.IsAvailable)
        {
            Text = "Network is available";
        }
        else
        {
            Text = "Network unavailable";
        }

Note that I needed to add a reference to Microsoft.VisualBasic to my project.

难道不是整个VB库中的“我的”东西吗?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM