February 23, 2015

Get info about your machine

Today’s article is about a static class from .NET Framework which provides some information about your machine and platform used – System.Environment. I find this class immensely useful only for some very specific tasks, because not every application could benefit from what it provides. I’ll discuss only few of its public members, because it’s quite well documented on MSDN.


I use this when I need to know a full path of a configuration file or any other resource file on a disk in case I placed it in the same folder as my application binaries are placed.

var path = Path.Combine(Environment.CurrentDirectory, "config.xml");

But there’s one catch, this does not work with Windows services, because when they are started by a system, their default working directory is in C:\Windows\System32 since Service Control Manager is placed there. So if you are not sure if your code will run from a Windows service, it’s safer to use something like as follows.

Path.GetDirectory(new Uri(Assembly.GetExecutingAssembly().CodeBase).LocalPath);


No need to describe, I just want to point it out, because I use it a client or server identifier in a network communication.


This one is not really self-explanatory and can be easily overlooked, but I place it among my best findings in .NET Framework. Have you ever tried to debug a Windows Service? Right, not a very pleasant business. This could make a whole nother article, so here’s a random example for now, maybe I’ll do one later myself.


You probably know how to access command line arguments from a console application, but how to access then from a WinForms app or a class library? That’s where Environment.GetCommandLineArgs() shines. Just know that the first arguments is always a path to the executing assembly or just its name, it depends where a working directory is.


An easy way to get paths to many special system folders like Desktop, MyDocuments or Program Files.

No comments:

Post a Comment