Zayko in the Net

Personal blog of Vitaly Zayko


Where “Send To” in Windows 7?

Long time ago I have found useful to add some custom shortcuts to “Send To” folder in Windows. Most useful for me is shortcut to Notepad: if you have this shortcut in “Send To”, when you need to open any text file (or HTML, or XML – you name it) you just need to select that file in Windows Explorer, right click on it and under “Send To” select the Notepad shortcut. Simply, isn’t it?

It is not always easy to locate this folder. Because Windows 7 is coming and I already switched to Win7 RC, this tip applies to Win7. Here is the path: C:\Users\<user name>\AppData\Roaming\Microsoft\Windows\SendTo

Note: folder “AppData” is system and hidden by default, thus if you hate to type the entire path manually, open C:\Users\<user name>\ location then type “AppData” in address bar and then you can use your mouse to navigate to “SendTo”.

SendTo folder in Windows 7

How to shrink LOG files in Microsoft SQL Server 2005 and 2008

You know that LOG files of actively used SQL Server databases could become huge, even bigger than data (MDF) file.
In SQL2005 you can use this script to shrink LOG file size:

USE <database name>
DBCC SHRINKFILE(<log file name>, <preferred size>)

But this is no longer working in SQL2008. So do this:

USE <database name>
DBCC SHRINKFILE(<log file name>, <preferred size>)

Good luck!

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;

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:


In non-WinForms Apps use this:


Note that last back slash is not included.

How to create Windows shortcut (C#)

1. First of all, add reference to Windows Script Host Object model:

Add Reference to Windows Script Host Object Model

2. Add Namespace:

// Add namespace reference:
using IWshRuntimeLibrary;

3. Add the code below to your App. Note: I didn't assign all IWshShortcut properties just mostly used so please check all properties by yourself.

/// <summary>
/// Create Windows Shorcut
/// </summary>
/// <param name="SourceFile">A file you want to make shortcut to</param>
/// <param name="ShortcutFile">Path and shorcut file name including file extension (.lnk)</param>
public void CreateShortcut(string SourceFile, string ShortcutFile)
   CreateShortcut(SourceFile, ShortcutFile, null, null, null, null);

/// <summary>
/// Create Windows Shorcut
/// </summary>
/// <param name="SourceFile">A file you want to make shortcut to</param>
/// <param name="ShortcutFile">Path and shorcut file name including file extension (.lnk)</param>
/// <param name="Description">Shortcut description</param>
/// <param name="Arguments">Command line arguments</param>
/// <param name="HotKey">Shortcut hot key as a string, for example "Ctrl+F"</param>
/// <param name="WorkingDirectory">"Start in" shorcut parameter</param>
public void CreateShortcut(string SourceFile, string ShortcutFile, string Description,
   string Arguments, string HotKey, string WorkingDirectory)
   // Check necessary parameters first:
    if (String.IsNullOrEmpty(SourceFile))
       throw new ArgumentNullException("SourceFile");
   if (String.IsNullOrEmpty(ShortcutFile))
       throw new ArgumentNullException("ShortcutFile");

   // Create WshShellClass instance:
    WshShellClass wshShell = new WshShellClass();

   // Create shortcut object:
    IWshRuntimeLibrary.IWshShortcut shorcut = (IWshRuntimeLibrary.IWshShortcut)wshShell.CreateShortcut(ShortcutFile);

   // Assign shortcut properties:
    shorcut.TargetPath = SourceFile;
   shorcut.Description = Description;
       shorcut.Arguments = Arguments;
   if (!String.IsNullOrEmpty(HotKey))
       shorcut.Hotkey = HotKey;
   if (!String.IsNullOrEmpty(WorkingDirectory))
       shorcut.WorkingDirectory = WorkingDirectory;

   // Save the shortcut:

4. And here is how to call function you just added:

// Make sure you use try/catch block because your App may has no permissions on the target path!
   CreateShortcut(@"C:\MySourceFile.exe", @"C:\MyShortcutFile.lnk", 
       "Custom Shortcut", "/param", "Ctrl+F", @"c:\");
catch (Exception ex)

Code formatted by SaveAsHtml - a free Visual Studio 2008 plugin
Technorati Tags: ,

How to open file by associated program? (C#)

If you are familiar with Win32 API then you should know function ShellExecute which performs some operations on files including opening in programs associated with this particular file type.

In .NET Framework world you can use this function through PInvoke but there is a managed mechanism to do the same:

using (System.Diagnostics.Process prc = new System.Diagnostics.Process())
   prc.StartInfo.FileName = "c:\\test.txt";