Zayko in the Net

Personal blog of Vitaly Zayko

NAVIGATION - SEARCH

How to get some User environment information? (C#)

Use System.Environment namespace to get lot of information about your user. Just few examples:

 

string userName = System.Environment.UserName;
string machineName = System.Environment.MachineName;
OperatingSystem osVersion = System.Environment.OSVersion;
string userDomainName = System.Environment.UserDomainName;

How to get list of removable drives installed on a computer? (C#)

First of all add reference to System.Management sysm assembly.
Then run something like this:

1:/// <summary>
2:/// Retuns list of all Removable drives aailable
3:/// </summary>
4:/// <param name="UsbDrives">Structure to store drive names (e.g. "D:", "E:" etc.</param>
5:/// <returns>true if at least one removable is available</returns>
6:public bool GetRemovableDisks(out IList<string> UsbDrives)
7:{
8:   // Add System.Management reference. Then
9:    bool result = false;
10:   UsbDrives = new List<string>();
11:   using (System.Management.ManagementClass managementClass = new System.Management.ManagementClass("Win32_Diskdrive"))
12:   {
13:       using (System.Management.ManagementObjectCollection driveCollection = managementClass.GetInstances())
14:       {
15:           foreach(System.Management.ManagementObject driveObject in driveCollection)
16:               foreach (System.Management.ManagementObject drivePartition in driveObject.GetRelated("Win32_DiskPartition"))
17:                   foreach (System.Management.ManagementBaseObject logicalDisk in drivePartition.GetRelated("Win32_LogicalDisk"))
18:                   {
19:                       string drive = (logicalDisk["Name"]).ToString();
20:                       string driveDescription = logicalDisk.Properties["Description"].Value.ToString();
21:                       if (driveDescription.Equals("Removable Disk", StringComparison.InvariantCultureIgnoreCase))
22:                       {
23:                           UsbDrives.Add(drive);
24:                           result = true;
25:                       }
26:                   } 
27:       }
28:   }
29:   return result;
30:}
31:

How to get path to running Assembly? (C#)

In this post I explained how to find this directory in .NET Compact Framework. Here is how to do this in desktop Applications.

If you are working on a Windows Forms App you, can make this call:

System.IO.Path.GetDirectoryName(Application.ExecutablePath);

In non-WinForms Apps use this:

System.IO.Path.GetDirectoryName(
System.Reflection.
Assembly.GetEntryAssembly().Location);

Note that last back slash is not included.