How to Calculate the Difference in Months Between two Dates C#

This code snippet lets you calculate the difference in months between two dates.

If all you want is simply a difference in the months -completely disregarding the date values- then you can use this:

public static int MonthDifference(this DateTime lValue, DateTime rValue)
    return (lValue.Month - rValue.Month) + 12 * (lValue.Year - rValue.Year);

Note that this returns a relative difference, meaning that if rValue is greater than lValue, then the return value will be negative. If you want an absolute difference, you can use this:

public static int MonthDifference(this DateTime lValue, DateTime rValue)
    return Math.Abs((lValue.Month - rValue.Month) + 12 * (lValue.Year - rValue.Year));

How to Print an Existing Excel File Using C#

In this tutorial I will show you how to print a Excel file using a WPF app. You might also want to look at a related post.

Create and Download Excel File Using PHP

Step 1: Add a reference to Excel Interop in your Project

Add a reference to Microsoft.Office.Interop.Excel in your project by right clicking on References, Add Reference from the Solution Explorer. Next choose Microsoft.Office.Interop.Excel from the Extensions tab under Assemblies.

Add a using statement at the top of the page in which you want to add the print XlS function.

using Excel= Microsoft.Office.Interop.Excel;

Step 2: Define Public Variables for Excel

Define the following variables before the class constructor.

public Excel.Application APP = null;
public Excel.Workbook WB = null;
public Excel.Worksheet WS = null;
public Excel.Range Range = null;  

Step 3: Add the Method to Print Excel

The following function opens a Excel file to print it and then closes it again.

void PrintMyExcelFile()
    this.APP = new Microsoft.Office.Interop.Excel.Application(); 

    // Open the Workbook:
    this.Open("C:\\Users\\maska\\Documents\\MyExcel.xlsx", 1);

    // Get the first worksheet.
    // (Excel uses base 1 indexing, not base 0.)
    WS = (Excel.Worksheet)WB.Worksheets[1];

    // Print out 1 copy to the default printer:
        Type.Missing, Type.Missing, Type.Missing, Type.Missing,
        Type.Missing, Type.Missing, Type.Missing, Type.Missing);

    // Cleanup:


    WB.Close(false, Type.Missing, Type.Missing);


That’s it. Call this method to print an existing excel file.

How to Hide and Show the Console Window Associated with your own C# app?

Here’s how:

Add a reference to InteropServices in your class.

using System.Runtime.InteropServices;

Next, define two function signatures GetConsoleWindow and ShowWindow. These functions use kernel32.dll and user32.dll respectively.

static extern IntPtr GetConsoleWindow();

static extern bool ShowWindow(IntPtr hWnd, int nCmdShow);

const int SW_HIDE = 0;
const int SW_SHOW = 5;

Finally, use these functions as follows. Get the handle by calling the GetConsoleWindow function.

var handle = GetConsoleWindow();

To hide a Window:

// Hide
ShowWindow(handle, SW_HIDE);

To show a Window:

// Show
ShowWindow(handle, SW_SHOW);

How to get the Month Name in C#?

You can use the CultureInfo to get the month name. Another way is to use extension methods. Here is an example of how to do it using extension methods:

Add a DateTimeExtensions class to your project.

static class DateTimeExtensions
    public static string ToMonthName(this DateTime dateTime)
        return CultureInfo.CurrentCulture.DateTimeFormat.GetMonthName(dateTime.Month);

    public static string ToShortMonthName(this DateTime dateTime)
        return CultureInfo.CurrentCulture.DateTimeFormat.GetAbbreviatedMonthName(dateTime.Month);

Now you can simply use these extension methods in your project like any other DateTime method.

using System;
using System.Globalization;

class Program
    static void Main()


How to disable Hardware Back button in Windows Phone App

Sometimes there may be a situation when you wish to prompt the user before exiting the page or frame of the application. So you need to control the back button function at that time.

Here is the code to disable the back button and perform your own function on pressing the back button.


Silverlight (Windows phone 8/8.1)

In the constructor of the page you need to add the following code as shown in the figure below



For example you wish to prompt the user before exiting the app then you can add the following code on your MainPage.



WinRT (Windows phone 8.1/10)

In the constructor of the page or frame you need to add the following code as shown in the figure below




I hope this post will be helpful to you

Retrieve File Size From Remote URL using C#

The system API class System.Net.HttpWebRequest allows you to retrieve the file information programmatically. The size of each file/page generally available in the header section of web response, which you can query to get it.
Header contains Content-Length property value which gives you the size of the file in bytes. This you can later calculate to convert in MB or GB.

Here’s the source code that can be used:

private static string GetFileSize(Uri uriPath)
     var webRequest = HttpWebRequest.Create(uriPath);
     webRequest.Method = "HEAD";
     using (var webResponse = webRequest.GetResponse())
        var fileSize = webResponse.Headers.Get("Content-Length");
        var fileSizeInMegaByte = Math.Round(Convert.ToDouble(fileSize) / 1024.0 / 1024.0, 2);
        return fileSizeInMegaByte + " MB";

How to Execute a Command in C# ?

This article will help you to execute a command in C#, just like we execute a command using the Windows command prompt

The code given below creates a process i.e. a command process and then invokes the command that we want to execute. The result of the command is stored in a string variable, which can then be used for further reference. The command execution can happen in two ways, synchronously and asynchronously. In the asynchronous command execution, we just invoke the command execution using a thread that runs independently.

Below is the code to execute the command synchronously:

/// <span class="code-SummaryComment"><summary></span>
/// Executes a shell command synchronously.
/// <span class="code-SummaryComment"></summary></span>
/// <span class="code-SummaryComment"><param name="command">string command</param></span>
/// <span class="code-SummaryComment"><returns>string, as output of the command.</returns></span>
public void ExecuteCommandSync(object command)
         // create the ProcessStartInfo using "cmd" as the program to be run,
         // and "/c " as the parameters.
         // Incidentally, /c tells cmd that we want it to execute the command that follows,
         // and then exit.
    System.Diagnostics.ProcessStartInfo procStartInfo =
        new System.Diagnostics.ProcessStartInfo("cmd", "/c " + command);

    // The following commands are needed to redirect the standard output.
    // This means that it will be redirected to the Process.StandardOutput StreamReader.
    procStartInfo.RedirectStandardOutput = true;
    procStartInfo.UseShellExecute = false;
    // Do not create the black window.
    procStartInfo.CreateNoWindow = true;
    // Now we create a process, assign its ProcessStartInfo and start it
    System.Diagnostics.Process proc = new System.Diagnostics.Process();
    proc.StartInfo = procStartInfo;
    // Get the output into a string
    string result = proc.StandardOutput.ReadToEnd();
    // Display the command output.
      catch (Exception objException)
      // Log the exception

The above code invokes the cmd process specifying the command to be executed. The option procStartInfo.RedirectStandardOutput is set to true, since we want the output to be redirected to the StreamReader. The procStartInfo.CreateNoWindow property is set to true, as we don’t want the standard black window to appear. This will execute the command silently.

Below is the code to execute the command asynchronously:

/// <span class="code-SummaryComment"><summary></span>
/// Execute the command Asynchronously.
/// <span class="code-SummaryComment"></summary></span>
/// <span class="code-SummaryComment"><param name="command">string command.</param></span>
public void ExecuteCommandAsync(string command)
    //Asynchronously start the Thread to process the Execute command request.
    Thread objThread = new Thread(new ParameterizedThreadStart(ExecuteCommandSync));
    //Make the thread as background thread.
    objThread.IsBackground = true;
    //Set the Priority of the thread.
    objThread.Priority = ThreadPriority.AboveNormal;
    //Start the thread.
   catch (ThreadStartException objException)
    // Log the exception
   catch (ThreadAbortException objException)
    // Log the exception
   catch (Exception objException)
    // Log the exception

If we observe carefully, the asynchronous execution of the command actually invokes the synchronous command execution method using a thread. The thread runs in the background making the command execution asynchronous in nature.

What’s the difference between String and string?

In C#, what is the difference between String and string? (note the case)

string is an alias in C# for System.String. So technically, there is no difference. It’s like int vs. System.Int32.

As far as guidelines, I think it’s generally recommended to use string any time you’re referring to an object. e.g.

string place = "world";

Likewise, I think it’s generally recommended to use String if you need to refer specifically to the class.

string greet = String.Format("Hello {0}!", place);

Here are a few noteworthy points about both:

  • string is just an alias for System.String. The compiler will treat them identically.
  • string is a reserved word, but String is just a class name. This means that string cannot be used as a variable name by itself.
  • You can’t use String without using System; beforehand.
  • string is a type in C#. System.String is a type in the CLR.
  • You can’t use string in reflection; you must use String.

You can do more localized aliasing for types and namespaces with the using keyword. e.g.

using str = System.String;
str s = "Now you've got another alias for string!";

String and Other Aliases

string is an alias for System.String. They compile to the same code, so at execution time there is no difference whatsoever. This is just one of the aliases in C#. The complete list is:

object:  System.Object
string:  System.String
bool:    System.Boolean
byte:    System.Byte
sbyte:   System.SByte
short:   System.Int16
ushort:  System.UInt16
int:     System.Int32
uint:    System.UInt32
long:    System.Int64
ulong:   System.UInt64
float:   System.Single
double:  System.Double
decimal: System.Decimal
char:    System.Char

How to Fix IpOverUsbSvc error while registering Windows Phone device

Sometimes while registering your Windows Phone device for development you might get a IpOverUsbSvc error.

Here’s how to register your device for development.

A simple fix that seems to work most of the times is to restart the service. Here’s how to do it.

Step 1: Open Powershell in Admin mode

Go to start and search for Powershell. Open it in Administrator mode by right clicking.


Step 2: Run the commands to restart the service

Run the following commands to restart the IpOverUsbSvc service.