These I was on a snowy night coding away and I needed to get the name of the computer as I needed it for a ...
well that is another story for another time :) lets get onto some more important things like code, oh yeah!
I know that in C# all one has to do is call upon:
string computerName = Environment.MachineName;
Console.WriteLine(computerName);
And there it is, all nice and pretty just waiting for you use.
The problem with this is that it is just way too boring and to be honest I am getting a little bored writing code in C# these days as it seems it just wants to do everything for you and personally I miss the C++ days (Java, C++ you guys listening, I am looking at you once again), so I figured I would go ahead and pull up my sleeves and have just a little fun even if only for a few mere minutes.
First I added the wonderful little include, wait I mean using ;)
using System.Runtime.InteropServices;
Then in the little util class I have going on, I added this little gem of an import.
public class Utility
{
[ DllImport( "kernel32.dll" ) ]
private static extern unsafe bool GetComputerNameW( char* name, ref ulong size );
...
}
Ah refreshing, takes me back a few years. Beautiful isn’t it?
Next I wrapped this beauty around a little function called getComputerName
public static string getComputerName()
{
string computerName = String.Empty;
// Dont forget to add unsafe.
unsafe
{
ulong size = 256; // Set size for allocation.
char* name = stackalloc char[ (int)size ]; // Allocate memory.
bool success = GetComputerNameW( name, ref size ); // Get computername.
for ( uint i = 0; i < size; i++, name++ ) // Assign to the string.
computerName += *name;
}
return computerName;
}
Function Complete! Would you look at that!
I better step away from the screen for a few minutes as I wipe away the tears…
Ok, back.
Now to use it, well, you will just call it:
string comp = Utility.getComputerName();
Console.WriteLine(comp);
Now come on, be honest, wasn’t that so much more fun than calling Environment.MachineName?
I say yes, but then again, that is just little OLD me, OLD keyword !
KDWAG out until next time…
Happy coding and Merry Christmas! Ok, not Christmas yet but soon I tell you soon!