tags:

views:

159

answers:

3

I need a way to uniquely identify a computer using .NET that works in both Windows and Linux.

The methods used in both operational system do not have to be the same. That is: I can have an approach for Mono running on Linux and another approach for .NET running on Windows.

I took a look at another similar question on SO and it seems that the default way to identify the computer with .NET is using WMI, but will that work in a Mono machine whatever the OS is?

I'm open to suggestions. Thanks in advance.

+1  A: 

No, WMI will not work on Mono.

jpobst
+1  A: 

Would getting the MAC address work?

Nick DeVore
+2  A: 

I'm in the middle of getting one of our C#/.Net applications to work on Linux... So I know what you're going through, having to find ways to get around the differences between Linux and Windows.

Now this is very, very hacky, and this is just a rough draft I threw together for you. There's probably a better way to do it, but maybe it will give you an idea...

bool IsRunningMono()
{
    // With our application, it will be used on an embedded system, and we know that
    // Windows will never be running Mono, so you may have to adjust accordingly.
    return Type.GetType("Mono.Runtime") != null;
}

string GetCPUSerial()
{
    string serial = "";

    if(IsRunningMono())
    {
        ProcessStartInfo startInfo = new ProcessStartInfo();
        startInfo.FileName = "lshw";
        startInfo.Arguments = "-xml";
        startInfo.UseShellExecute = false;
        startInfo.RedirectStandardOutput = true;

        using(Process p = Process.Start(startInfo))
        {
            p.WaitForExit();
            System.Xml.XmlDocument xdoc = new System.Xml.XmlDocument();

            xdoc.Load(new System.Xml.XmlTextReader(new StringReader(p.StandardOutput.ReadToEnd())));

            System.Xml.XmlNodeList nodes = xdoc.SelectNodes("node/node/node/serial");

            if (nodes.Count > 0)
            {
                serial = nodes[0].InnerText;              
            }
        }        
    }
    else
    {
       // process using wmi
    }

    return serial;
}

I tried loading it into a DataSet instead of an XmlDocument, but it failed every time. Tested on Ubuntu 9.10. Hope this gets you going in the right direction.

JohnForDummies
Just check for http://msdn.microsoft.com/en-us/library/system.operatingsystem.platform.aspx instead of Type.GetType("Mono.Runtime").
skolima