C# Base64 String to PNG Image

Here’s how you can save a base64 encoded string to image file in C#.

public void SaveImageFile(string filename, string base64Image)
{
    string destinationImgPath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + Constants.UserImagesPath+"\\"+filename+".png";
    try
    {
        Directory.CreateDirectory(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + Constants.UserImagesPath);
    }
    catch (IOException iox)
    {
        Console.WriteLine(iox.Message+" "+iox.Data);
    }
    var bytes = Convert.FromBase64String(base64Image);
    using (var imageFile = new FileStream(destinationImgPath, FileMode.Create))
    {
        imageFile.Write(bytes, 0, bytes.Length);
        imageFile.Flush();
    }
}

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()
    {

        Console.WriteLine(DateTime.Now.ToMonthName());
        Console.WriteLine(DateTime.Now.ToShortMonthName());
        Console.Read();
    }
}

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)
{
     try
     {
         // 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;
    proc.Start();
    // Get the output into a string
    string result = proc.StandardOutput.ReadToEnd();
    // Display the command output.
    Console.WriteLine(result);
      }
      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)
{
   try
   {
    //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.
    objThread.Start(command);
   }
   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.
e.g.

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

Dictionary in C#

Dictionary<TKey, TValue> provide fast lookups, based on keys, to get values. With them, we use keys and values of any type, including int and string. Dictionary is used with different elements. We specify its key type and its value type (string, int).

Define a Dictionary

We specify its key type and its value type (string, int).

Add elements to a Dictionary

Here’s how to add elements to a Dictionary.

Read and update existing values

To read a value use the following statement.

To update an existing value simply use the following.

Check if a key exists in a Dictionary

This sees if a given string is present in a Dictionary.

Iterate through a Dictionary

Here we loop over KeyValuePairs in a Dictionary. With collections like Dictionary, we must always know the value types. With each KeyValuePair, there is a Key member and Value member.

Remove elements from a Dictionary

Here’s how you can remove elements from a Dictionary.

Count elements in a Dictionary

This computes the total number of keys in a Dictionary. This is simpler than accessing the Keys property, or looping over the Dictionary to count it.

Clear all elements from a Dictionary

We can erase all pairs with the Clear method.

Check if a value exists in a Dictionary

This method lacks the constant-time look up speed of ContainsKey. It instead searches the entire collection.

Get all keys of a Dictionary

Here we use the Keys property. We then look through each key and look up the values.

Get Root Domain and Favicon from URL in C#

In this quick tip I will show you a simple way to retrieve Root Domain and favicon icon from URL using C#. Its quite useful if you are building some kind of a newsreader app and wish to display the source of a news article in a proper way. Use the displayRootDomain method that takes url as input and gets the root domain and favicon.

This works for most URLs but I can’t guarantee if it will work for all links.

Cancelling an Async Task

Sometimes you may need to cancel a running asynchronous task, this following tutorial will show you how. Here’s how your task will work without an async cancellation.

Step 1: Create a new Windows Phone 8/8.1 Project

Start Visual Studio and create a new Windows Phone 8/8.1 project.

Step 2: In the MainPage.xaml paste the following code

Step 3: In the MainPage.xaml.cs above the constructor declare our CancellationTokenSource

 

CancellationTokenSource.Token property of cancellationToken is passed into our asynchronous task as an argument, while doing work the task can check the token to see if cancellation has been requested.

 

Step 4: Thereafter paste the following methods below the constructor


When the restart button is clicked, we cancel the current CancellationTokenSource which will stop the running task, we then instantiate a new CancellationTokenSource & start a new task. Here’s how it works,

Download the project source code and use it as a reference.

Download AsyncCancel.zip

Save Speech Synthesis Stream as Audio in Windows Phone 8.1

In Windows Phone 8.1 you can generate a SpeechSynthesisStream using text to speech. We earlier tipped you on
Using text to speech in Windows Phone 8 and 8.1
You can use the output SpeechSynthesisStream and save it as a .wav audio file in app’s local storage.

Note

This is not the best method to save the speech stream to audio as it takes a long time to get processed.

Sound off in comments/forums if you find a workaround.

UPDATE: We just found another method to do it and it seems to be quite faster. The sample Transcoding media project uses Windows.Media.Transcoding API to transcode a media file in a Windows Store app.