Zayko in the Net

Personal blog of Vitaly Zayko


Odd or Even? (C#)

How to quickly determine is given number odd or even? There are several simple methods.

Here is the first one:


 public bool IsEven(int i)
     return (i & 1) == 0;

And the second:

 public bool IsEven(int i)
     return (i % 2) == 0;


Technorati Tags:

Another way to get path to a running assembly or how to get list of command line arguments in a non console App?

There is an another way how to get path to a running assembly from itself besides I mentioned here. Use this simple snippet:

string[] cmd = Environment.GetCommandLineArgs();
string path_to_assembly = cmd[0];
/* cmd[1] and above contains command line arguments is any */

Resulting array is at least one element length or longer. First element of this array always contains path to the assembly. As a side effect – you can get command line params beginning from second element.

Unfortunately doesn’t work in .NET Compact Framework.

Technorati Tags: ,

Adding /r/n in .NET (C#)

When your App outputs some text, you probably will want to split your strings by adding carriage return. Of course, you can declare this as a constant string: private const string CRLF = "/r/n";

or use predefined constant from Environment: Environment.NewLine

Using Windows 7 Jump List in Visual Studio 2010 Beta 2

If you are on Windows 7, you probably have noticed about new feature – Windows 7 Jump List. If you right-click on an App icon (let say – Internet Explorer) you will see additional menu items which you as a programmer can handle in your solutions. If you are on Visual Studio 2008, the only way is to use an additional Windows API Code Pack for Microsoft .NET Framework. But there is a modern way for Visual Studio 2010 (at least for WPF):

  • Open App.xaml file of your App
  • Add reference to JumpList as shown below:

<Application x:Class="WpfApplication1.App"






    <!-- Add reference to JumpList here: -->


        <JumpList ShowFrequentCategory="True" ShowRecentCategory="True">

            <JumpTask Title="Notepad"

                      Description="Open Notepad"






Technorati Tags: ,,

C#: How To Disable Windows Screensaver programmatically?

In some cases you may want to prevent Windows screensaver from running. For example, when a customer watch video or does VoIP call, his mouse and keyboard activities are low.

I didn’t find a managed function in .NET Framework but fortunately we can make it through PInvoke.

1. Add PInvoke namespace:

using System.Runtime.InteropServices;

2. Import SystemParametersInfo function and its enums as below:

public enum SPI : uint
public enum SPIF : uint
   None = 0x00,
[DllImport("user32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
static extern bool SystemParametersInfo(SPI uiAction, uint uiParam, ref uint pvParam, SPIF fWinIni);
[DllImport("user32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
static extern bool SystemParametersInfo(SPI uiAction, uint uiParam, uint pvParam, SPIF fWinIni);

3. You may want to check is screensaver enabled by Control panel setting or not:

uint vParam = 0;
if (SystemParametersInfo(SPI.SPI_GETSCREENSAVEACTIVE, 0, ref vParam, SPIF.None))
   if (vParam == 1)
       MessageBox.Show("Screensaver is enabled");
        MessageBox.Show("Screensaver is disabled");

4. And finally - disable it:

if (SystemParametersInfo(SPI.SPI_SETSCREENSAVEACTIVE, 0, 0, SPIF.None))
   MessageBox.Show("Screensaver has been disabled");

5. Don’t forget to re-enable if it was enabled initially:

SystemParametersInfo(SPI.SPI_SETSCREENSAVEACTIVE, 1, 0, SPIF.None);

How to send HTML e-mail with an image embedded in its body? (C#)

I’m trying to cover two common questions in one post:

  1. How to send an HTML message by SMTP?
  2. How to embed a picture into its body?

Follow the C# code below.

// Use AlternateView to create HTML body ("cid:image" - here we place the image):
using(AlternateView htmlView = AlternateView.CreateAlternateViewFromString(
   "This is an <b>Html</b> e-mail message with <i>embedded image</i> below\r\n<img src='cid:image'>",
   null, "text/html"))
   // Create LinkedResource to specify an embedded image:
    using (LinkedResource image = new LinkedResource("c:\\IMAGE.jpg"))
       // ContentId should be equals to the CID that we specified above
        image.ContentId = "image";


       // Create SmtpClient as reqular:
        SmtpClient smtp = new SmtpClient("");

       // Set Credential if needed:
        smtp.Credentials = new System.Net.NetworkCredential("mailusername", "mailpassword");

       // ...and here we go:

How to lock workstation programmatically? (C#)

There is no such .NET function (or at least I didn’t find). Fortunately we can use PInvoke instead.
Use this function to lock workstation’s display to protect from unauthorized use. Result of this function is the same as pressing Ctrl+Alt+Del.
  1. Add namespace at the top of your code:
    	using System.Runtime.InteropServices;
  2. Declare PInvoke:
    	[DllImport("user32.dll", SetLastError = true)]
    	static extern bool LockWorkStation();
  3. Call this function like this:
    	if (!LockWorkStation())
    	   throw new Win32Exception(Marshal.GetLastWin32Error());

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)
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;