.net, programming

How to use the My Namespace in C#

When I was first trying to transition from VB.NET to C# I found it pretty odd that the “My” Namespace wasn’t available in C#.  If you aren’t aware of what I’m talking about, the Microsoft.VisualBasic.MyServices namespace (My in Visual Basic) provides easy and intuitive access to a number of .NET Framework classes, enabling you to write code that interacts with the computer, application, settings, resources, and so on.

After a little hunting I discovered that by simply adding a reference and a using statement that I could be up and running with my beloved My classes that I had come to know and love.  Here’s how you do it…

Add a Reference

  1. In Solution Explorer, right-click the References node, and select Add Reference.
  2. When the References dialog box appears, scroll down the list, and select Microsoft.VisualBasic.dll.You might also want to include the following line in the using section at the start of your program.
    using Microsoft.VisualBasic.Devices;

Example

This example calls various static methods contained in the MyServices namespace. For this code to compile remember that we added a reference to Microsoft.VisualBasic.DLL in the step above.

using System;
using Microsoft.VisualBasic.Devices;
 
class TestMyServices
{
    static void Main()
    {
        // Play a sound with the Audio class:
        Audio myAudio = new Audio();
        Console.WriteLine("Playing sound...");
        myAudio.Play(@"c:\WINDOWS\Media\chimes.wav");
 
        // Display time information with the Clock class:
        Clock myClock = new Clock();
        Console.Write("Current day of the week: ");
        Console.WriteLine(myClock.LocalTime.DayOfWeek);
        Console.Write("Current date and time: ");
        Console.WriteLine(myClock.LocalTime);
 
        // Display machine information with the Computer class:
        Computer myComputer = new Computer();
        Console.WriteLine("Computer name: " + myComputer.Name);
 
        if (myComputer.Network.IsAvailable)
        {
            Console.WriteLine("Computer is connected to network.");
        }
        else
        {
            Console.WriteLine("Computer is not connected to network.");
        }
    }
}

Not all the classes in the MyServices namespace can be called from a C# application. You can visit this MSDN article that details more on what’s not supported.

Tagged , ,

Leave a Reply

Your email address will not be published. Required fields are marked *