Zayko in the Net

Personal blog of Vitaly Zayko

NAVIGATION - SEARCH

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.

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;
   if(!String.IsNullOrEmpty(Arguments))
       shorcut.Arguments = Arguments;
   if (!String.IsNullOrEmpty(HotKey))
       shorcut.Hotkey = HotKey;
   if (!String.IsNullOrEmpty(WorkingDirectory))
       shorcut.WorkingDirectory = WorkingDirectory;

   // Save the shortcut:
    shorcut.Save();
}

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!
try
{
   CreateShortcut(@"C:\MySourceFile.exe", @"C:\MyShortcutFile.lnk", 
       "Custom Shortcut", "/param", "Ctrl+F", @"c:\");
}
catch (Exception ex)
{
   MessageBox.Show(ex.Message);
}

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";
   prc.Start();
}

Enjoy!

How to convert System.Drawing.Color to a Html representation (C#)?

If you are working on some Web-related App then you sooner or later will need to convert a System.Drawing.Color structure to its Html format. Below are three overloaded functions.

        /// <summary>
/// Convert System.Drawing.Color struct to a Html color representation
/// </summary>
/// <param name="color">System.Drawing.Color struct to convert from</param>
/// <returns>Html color format as a string</returns>
public string ToHtmlColor(Color color)
{
   return "#" + color.ToArgb().ToString("x").Substring(2);
}

/// <summary>
/// Convert Red, Green and Blue components to a Html color representation
/// </summary>
/// <param name="r">The Red component value</param>
/// <param name="g">The Green component value</param>
/// <param name="b">The Blue component value</param>
/// <returns>Html color format as a string</returns>
public string ToHtmlColor(int r, int g, int b)
{
   Color color = System.Drawing.Color.FromArgb(r, g, b);
   return "#" + color.ToArgb().ToString("x").Substring(2);
}

/// <summary>
/// Convert ARGB color to a Html color representation
/// </summary>
/// <param name="argb">ARGB color value</param>
/// <returns>Html color format as a string</returns>
public string ToHtmlColor(int argb)
{
   Color color = System.Drawing.Color.FromArgb(argb);
   return "#" + color.ToArgb().ToString("x").Substring(2);
}

Dispose pattern (C#)

Pretty common pattern: if you are working on a class that utilize either unmanaged resources or managed disposable classes, you need to make your class disposable as well.

    class DisposePatternClass : IDisposable
    {
       /// <summary>
        /// Doesn't allow to dispose same instance twice
        /// </summary>
        private bool disposed = false;

       /// <summary>
        /// Privately cleaning up both managed and unmanaged resources
        /// </summary>
        /// <param name="disposing">True is DisposePatternClass.Dispose() was called; false if disposing by GC</param>
        private void CleanUp(bool disposing)
       {
           if (!this.disposed)
           {
               if (disposing)
               {
                   // Disponse Managed resources here
                }

               // Clean up Unmanaged resources here
            }

           disposed = true;
       }

       /// <summary>
        /// Manual Dispose
        /// </summary>
        public void Dispose()
       {
           CleanUp(true);
           GC.SuppressFinalize(this);
       }

       /// <summary>
        /// Destructor
        /// </summary>
        ~DisposePatternClass()
       {
           CleanUp(false);
       }
   }

Have fun!

How to get Assembly version string (C#)?

First of all: in this post I'm talking about Assembly version, not its file version which is different thing:

Here you go:

/// <summary>
/// Returns version of the current Assembly
/// </summary>
/// <returns>Version string in format x.x.x.x</returns>
private string GetAppVersion()
{
   return Assembly.GetExecutingAssembly().GetName().Version.ToString();
}

How to get Assembly path in .NET Compact Framework? (C#)

It's not that easy as in WinForms:

 public string GetAssemblyPath()
 {
     return System.IO.Path.GetDirectoryName(
         System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase);
 }

Note: last back slash doesn't add!

How to check is your App running under Admin privileges (C#)?

You have to know this before your App does something that requires Administrator privileges. Actually it is quite easy:

using System.Security.Principal; public bool IsAdmin() { WindowsPrincipal principal = new WindowsPrincipal(WindowsIdentity.GetCurrent()); return principal.IsInRole(WindowsBuiltInRole.Administrator); }