<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Martijn's C# Programming Blog &#187; strings</title>
	<atom:link href="http://www.dijksterhuis.org/tag/strings/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.dijksterhuis.org</link>
	<description>Information, news about programming in C#</description>
	<lastBuildDate>Fri, 07 Aug 2009 21:26:47 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.1.3</generator>
		<item>
		<title>Manipulating Strings in C# -Replacing part of a string / Replacing all occurences of a sub-string</title>
		<link>http://www.dijksterhuis.org/manipulating-strings-in-csharp-replacing-part-string/</link>
		<comments>http://www.dijksterhuis.org/manipulating-strings-in-csharp-replacing-part-string/#comments</comments>
		<pubDate>Fri, 13 Feb 2009 02:04:05 +0000</pubDate>
		<dc:creator>Martijn</dc:creator>
				<category><![CDATA[Beginner]]></category>
		<category><![CDATA[Learn C#]]></category>
		<category><![CDATA[c#]]></category>
		<category><![CDATA[regex]]></category>
		<category><![CDATA[strings]]></category>

		<guid isPermaLink="false">http://www.dijksterhuis.org/?p=637</guid>
		<description><![CDATA[Very often you need to change part of a string, maybe just once, or many times over. Strings in .NET/C# are immutable we cannot actually change a string in-place. But we are able to work on copies. The code example below attaches two new methods to the C# string class. The ReplaceFirst method replaces the [...]<p>This is a post from <a href="http://www.dijksterhuis.org">Martijn's C# Coding Blog</a>. </p>
]]></description>
			<content:encoded><![CDATA[<p>Very often you need to change part of a string, maybe just once, or many times over. Strings in .NET/C# are immutable we cannot actually change a string in-place. But we are able to work on copies. The code example below attaches two new methods to the C# string class.</p>
<ul>
<li>The ReplaceFirst method replaces the first occurrence of &#8220;needle&#8221; in a string and replaces it with &#8220;replacement&#8221;.</li>
<li>The ReplaceAll function is similar: it steps through the string modifying it each time it finds &#8220;needle&#8221; and replaces it. To avoid a possible infinite loop it first checks whether &#8220;needle&#8221; is equivalent to &#8220;replacement&#8221;.</li>
</ul>
<p><span id="more-637"></span></p>
<pre class="brush: c#">
using System;
using System.Collections;

namespace StringItems
{
        static class StringExt
        {
                public static string ReplaceFirst(this string haystack, string needle, string replacement)
                {
                        int pos = haystack.IndexOf(needle);
                        if (pos &lt; 0) return haystack;

                        return haystack.Substring(0,pos) + replacement + haystack.Substring(pos+needle.Length);
                }

                public static string ReplaceAll(this string haystack, string needle, string replacement)
                {
                        int pos;
                        // Avoid a possible infinite loop
                        if (needle == replacement) return haystack;
                        while((pos = haystack.IndexOf(needle))&gt;0)
                                haystack = haystack.Substring(0,pos) + replacement + haystack.Substring(pos+needle.Length);
                        return haystack;
                }

        }
}
</pre>
<p>Both methods are implemented using a class extension. (for more on creating class extensions see also <a href="../manipulating-strings-in-csharp-finding-all-occurrences-of-a-string-within-another-string/">Finding all occurrences of a string within another string</a>) After you include these methods into your project you can call them directly from any string instance:</p>
<blockquote><p>string myString = &#8220;Hello World&#8221;;<br />
string myModifiedString = myString.ReplaceFirst(&#8220;World&#8221;,&#8221;People&#8221;);<br />
Console.WriteLine(&#8220;{0}&#8221;,myModifiedString); // Writes: &#8220;Hello People&#8221;</p></blockquote>
<p>An example use of the ReplaceAll method:</p>
<blockquote><p>string myString = &#8220;boo foo is not foo boo or foo boo foo&#8221;;<br />
string myModifiedString = myString.ReplaceFirst(&#8220;boo&#8221;,&#8221;goo&#8221;);<br />
Console.WriteLine(&#8220;{0}&#8221;,myModifiedString); // Writes: &#8220;goo foo is not foo goo or foo goo foo&#8221;;</p></blockquote>
<p><strong>Why not just use a regular expression?</strong></p>
<p><strong></strong>If you are familiar with the RegEx class in C# you can easily write a regular expression to achieve the same string replacement result:</p>
<blockquote><p>using System.Text.RegularExpressions;<br />
Regex regex = new Regex(&#8220;boo&#8221;);<br />
string result = regex.Replace(&#8220;boo foo is not foo boo or foo boo foo&#8221;, &#8220;goo&#8221;);</p></blockquote>
<p>Regular expressions are flexible and if you do anything more complex than just a basic string replacement they are your only choice. But they come at a hefty performance price. To run a regular expression it needs to be compiled first and then executed. The .NET runtime caches the expression for performance but using a regular expression for string replacement is still much slower.</p>
<p><strong>How much slower are regular expressions for string replacement?</strong></p>
<p>In an earlier post I described <a href="http://www.dijksterhuis.org/timing-function-performance-stopwatch-class/">the Stopwatch class in System.Diagnostics</a>. It is ideal for a little benchmark testing &#8212; so lets compare my string replacement methods with the build-in regular expression library:</p>
<pre class="brush: c#">
string haystack = &quot;boo foo is not foo boo or foo boo foo&quot;;
string result;
Stopwatch sw = Stopwatch.StartNew();
for (int Lp = 0; Lp &lt; 100000; Lp++)
result = regex.Replace($haystack, &quot;goo&quot;);
sw.Stop();
Console.WriteLine(&quot;Time used (float): {0} ms&quot;,sw.Elapsed.TotalMilliseconds);
</pre>
<p><span>And the same for the string replacement functions:</span></p>
<pre class="brush: c#">
string haystack = &quot;boo foo is not foo boo or foo boo foo&quot;;
string result;
Stopwatch sw = Stopwatch.StartNew();
for(int Lp = 0; Lp &lt; 100000; Lp++)
result = haystack.ReplaceAll(&quot;boo&quot;,&quot;goo&quot;);
sw.Stop();
Console.WriteLine(&quot;Time used (float): {0} ms&quot;,sw.Elapsed.TotalMilliseconds);
</pre>
<p>The regular expression code needed <strong>1100ms </strong>, whereas the string replacement code needed just<strong> 27ms</strong>. So for this particular example, the string replacement was <strong>40 times faster</strong> than a regular expression.</p>
<p>This is a post from <a href="http://www.dijksterhuis.org">Martijn's C# Coding Blog</a>. </p>
]]></content:encoded>
			<wfw:commentRss>http://www.dijksterhuis.org/manipulating-strings-in-csharp-replacing-part-string/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Manipulating Strings in C# &#8211; Finding all occurrences of a string within another string</title>
		<link>http://www.dijksterhuis.org/manipulating-strings-in-csharp-finding-all-occurrences-of-a-string-within-another-string/</link>
		<comments>http://www.dijksterhuis.org/manipulating-strings-in-csharp-finding-all-occurrences-of-a-string-within-another-string/#comments</comments>
		<pubDate>Wed, 11 Feb 2009 07:57:50 +0000</pubDate>
		<dc:creator>Martijn</dc:creator>
				<category><![CDATA[Beginner]]></category>
		<category><![CDATA[Learn C#]]></category>
		<category><![CDATA[c#]]></category>
		<category><![CDATA[extension]]></category>
		<category><![CDATA[strings]]></category>

		<guid isPermaLink="false">http://www.dijksterhuis.org/?p=633</guid>
		<description><![CDATA[A common programming problem is to find the position of all copies of a string in another string. For finding the first copy the C# string method IndexOf is similar to the C strpos() function. It returns the first occurrence of a string in another string. But what if you would like to find the [...]<p>This is a post from <a href="http://www.dijksterhuis.org">Martijn's C# Coding Blog</a>. </p>
]]></description>
			<content:encoded><![CDATA[<p>A common programming problem is to find the position of all copies of a string in another string.  For finding the first copy the C# string method IndexOf is similar to the C strpos() function. It returns the first occurrence of a string in another string. But what if you would like to find the position of all occurances of the substring?  The following &#8220;IndexOfAll&#8221; method does just that. It returns an IEnumerable containing the offsets of each sub-string in the main string.</p>
<p><span id="more-633"></span></p>
<p>Because you might want to use this code throughout your project it is implemented as an Extension class. Simply put: the IndexOfAll method is attached to the String class. So if we want to call it we can just use <string>.IndexOfAll(needle)</p>
<p>To be able to define an extension we need to create a static method and put it into a static class. The first parameter of the method identifies the class the method should associate with. In our case: string. We do this by defining it as &#8220;this string&#8221;.</p>
<pre class="brush: c#">
using System;
using System.Collections;

namespace StringItems
{
    static class StringExt
    {
        public static IEnumerable IndexOfAll(this string haystack, string needle)
        {
            int pos,offset = 0;
            while ((pos = haystack.IndexOf(needle))&gt;0)
            {
                haystack = haystack.Substring(pos+needle.Length);
                offset += pos;
                yield return offset;
            }
        }
    }

    class MainClass
    {
        public static void Main(string[] args)
        {
            string needle = &quot;x&quot;;
            string haystack = &quot;3 x 4 = 2 x 6 = 1 x 12&quot;;
            foreach(int Pos in haystack.IndexOfAll(needle))
                Console.WriteLine(&quot;Offset: {0}&quot;,Pos);
        }
    }
}
</pre>
<p>This is a post from <a href="http://www.dijksterhuis.org">Martijn's C# Coding Blog</a>. </p>
]]></content:encoded>
			<wfw:commentRss>http://www.dijksterhuis.org/manipulating-strings-in-csharp-finding-all-occurrences-of-a-string-within-another-string/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
		<item>
		<title>Using String.Split and String.Join to build a simple CSV reader and writer in C#</title>
		<link>http://www.dijksterhuis.org/stringsplit-stringjoin-build-simple-csv-reader-writer/</link>
		<comments>http://www.dijksterhuis.org/stringsplit-stringjoin-build-simple-csv-reader-writer/#comments</comments>
		<pubDate>Thu, 05 Feb 2009 07:14:38 +0000</pubDate>
		<dc:creator>Martijn</dc:creator>
				<category><![CDATA[Beginner]]></category>
		<category><![CDATA[Learn C#]]></category>
		<category><![CDATA[csv]]></category>
		<category><![CDATA[strings]]></category>

		<guid isPermaLink="false">http://www.dijksterhuis.org/?p=590</guid>
		<description><![CDATA[Whole programming languages have been designed (*cough* perl) so that we can cut delimited strings into bits and string them back together. For this purpose C# provides the String.Split() and String.Join() functions. You specify how you would like to split or merge the string and they do the work. In this post we look at [...]<p>This is a post from <a href="http://www.dijksterhuis.org">Martijn's C# Coding Blog</a>. </p>
]]></description>
			<content:encoded><![CDATA[<p><img src="http://www.dijksterhuis.org/wp-content/uploads/2009/02/535944717_08993f62a0_o.jpg" alt="Creating Delimited Strings in C#" title="Creating Delimited Strings in C#" width="500" height="178" class="alignnone size-full wp-image-598" /><br />
<em>Whole programming languages have been designed (*cough* perl) so that we can cut delimited strings into bits and string them back together. For this purpose C# provides the String.Split() and String.Join() functions. You specify how you would like to split or merge the string and they do the work. In this post we look at some common example uses and then put together a simple CSV (comma separated values) parser.</em></p>
<p><span id="more-590"></span><br />
<strong>Cutting a string using a delimiter </strong></p>
<blockquote><p>string Msg = &#8220;1997,Ford,E350,Super luxurious truck&#8221;;</p></blockquote>
<p>The String.Split function allows you to specify one or more separators. If we want to cut the above string at each comma we would do the following:</p>
<pre class="brush: c#">
string Msg = &quot;1997,Ford,E350,Super luxurious truck&quot;;
string[] Data = Msg.Split(new char[] {&#039;,&#039;});
int Cnt = 0;
foreach(string Field in Data)
Console.WriteLine(&quot;{0} = {1}&quot;,Cnt++,Field);
</pre>
<p><em>This outputs: </em></p>
<blockquote><p>0 = 1997<br />
1 = Ford<br />
2 = E350<br />
3 = Super luxurious truck
</p></blockquote>
<p>The split method takes an array of char[] as its parameter. It is possible to specify more than one separator. So if you would like to split a string on both comma&#8217;s and exclamation marks you could do the following:</p>
<pre class="brush: c#">
string Msg = &quot;The world is not enough ! I have one, two, no three! plans for conquering it&quot;;
string[] Data = Msg.Split(new char[] {&#039;,&#039;,&#039;!&#039;});
</pre>
<p>If you specify nothing at all then String.Split() will break on a predefined set of separators. These include spaces (all Unicode defined spaces), line breaks, tabs etc.</p>
<p>If you don&#8217;t want the returned array to contain empty strings, you can specify <em>StringSplitOptions.<span class="selflink">RemoveEmptyEntries</span></em></p>
<pre class="brush: c#">
string Msg = &quot;One,Two,,Four,,,Six,,Eight&quot;;
string[] Data = Msg.Split(new char[] {&#039;,&#039;},StringSplitOptions.RemoveEmptyEntries);
</pre>
<p><strong>Putting things back together again using String.Join()</strong></p>
<p>To quickly put things back together again we just String.Join(), its use is simple: You specify the character you would like to use to join, and pass an array of strings and the first element in the array to use. Lastly it is possible to limit the number of items Joined together.</p>
<blockquote><p>String[] val = {&#8220;ape&#8221;,&#8221;monkey&#8221;,&#8221;lion&#8221;,&#8221;human&#8221;,&#8221;woman&#8221;};<br />
Console.WriteLine(&#8220;{0}&#8221;, String.Join(&#8220;|&#8221;,val,0,4));</p></blockquote>
<p>This results in:</p>
<blockquote><p>ape|monkey|lion|human</p></blockquote>
<p><strong>Building a Comma Separated Values (CSV) reader / writer using String.Split and String.Join</strong></p>
<p>Comma Seperated Values files are created by spreadsheets (such as Excel, OpenOffice Calc), databases (Microsoft Access). They are used to quickly transport data between different programs.   As we can now split input, and put it back together again I have created a very simple CSV reader and writer. It can read and write a CSV file and for good measure display to contents on the console.</p>
<p><em>Note that this reader is very simple, it does not deal with many potential data formatting issues that are perfectly legal for a CSV file. If you intend to import large data sets from databases you will want to create something stronger. </em></p>
<p>To play with this code the following data set provides a little bit of history on Japanese car manufacturers. It contains the name of the company, its founding year, current number of employees and founders name.</p>
<p><em>Data.CSV</em></p>
<blockquote><p>Toyota,1937,316000,Kiichiro Toyoda<br />
Mazda,1920,39364,Jujiro Matsuda<br />
Honda,1948,167231,Soichiro Honda</p></blockquote>
<pre class="brush: c#">
using System;
using System.IO;
using System.Collections;
using System.Text;

namespace consoleoutput
{
	class MainClass
	{

		public static ArrayList ReadCSV(string FileName)
		{
			ArrayList DataRows = new ArrayList();

		    // Create a Streamreader and open the file
		    using (StreamReader sr = new StreamReader(FileName))
            {
                String line;
                // Read lines from the file until the end of
                // the file is reached.
                while ((line = sr.ReadLine()) != null)
                {
					// Skip over empty lines
					if (line.Length == 0) continue;

					// Split the line at the comma
					string[] DataColumn = line.Split(new char[] {&#039;,&#039;});

					// Add the row of data to the ArrayList
					DataRows.Add(DataColumn);
                }
            }

			return DataRows;
		}

		public static void WriteCSV(string FileName, ArrayList CSVData)
		{
		    // Create a StreamWriter and open the file
		    using (StreamWriter sw = new StreamWriter(FileName))
            {
				foreach(string[] CSVRow in CSVData)
				{
					string line = String.Join(&quot;,&quot;,CSVRow);
					sw.WriteLine(line);
				}
			}
		}

		public static void PrintCVS(ArrayList CSVData)
		{
			foreach(string[] CSVRow in CSVData)
			{
				string line = String.Join(&quot;,&quot;,CSVRow);
				Console.WriteLine(line);
			}
		}
		public static void Main(string[] args)
		{
			ArrayList myArrayList = ReadCSV(&quot;/home/martijn/cars.csv&quot;);
			PrintCVS(myArrayList);
			WriteCSV(&quot;/home/martijn/output.csv&quot;,myArrayList);
		}
	}
}
</pre>
<p>Image credit: <a rel="nofollow" href="http://www.flickr.com/photos/kacey/">Kacey</a></p>
<p>This is a post from <a href="http://www.dijksterhuis.org">Martijn's C# Coding Blog</a>. </p>
]]></content:encoded>
			<wfw:commentRss>http://www.dijksterhuis.org/stringsplit-stringjoin-build-simple-csv-reader-writer/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Encrypting and Decrypting a C# string</title>
		<link>http://www.dijksterhuis.org/encrypting-decrypting-string/</link>
		<comments>http://www.dijksterhuis.org/encrypting-decrypting-string/#comments</comments>
		<pubDate>Tue, 06 Jan 2009 06:31:27 +0000</pubDate>
		<dc:creator>Martijn</dc:creator>
				<category><![CDATA[Intermediate]]></category>
		<category><![CDATA[Learn C#]]></category>
		<category><![CDATA[decryption]]></category>
		<category><![CDATA[encryption]]></category>
		<category><![CDATA[md5]]></category>
		<category><![CDATA[strings]]></category>

		<guid isPermaLink="false">http://www.dijksterhuis.org/?p=453</guid>
		<description><![CDATA[The .NET C# library provides all the basic elements for encrypting a string with a passphrase and decrypting it later. Doing this however requires a few steps in between. This post show a simple set of routines to help you do just that. We use the TripleDES encryption suite to do the actual encryption, with [...]<p>This is a post from <a href="http://www.dijksterhuis.org">Martijn's C# Coding Blog</a>. </p>
]]></description>
			<content:encoded><![CDATA[<p><em>The .NET C# library provides all the basic elements for encrypting a string with a passphrase and decrypting it later. Doing this however requires a few steps in between. This post show a simple set of routines to help you do just that. We use the TripleDES encryption suite to do the actual encryption, with a little help from the MD5 hash sum generator.<br />
</em></p>
<p>The complete source code is listed below, but lets have a little look at how it works first.</p>
<p><span id="more-453"></span></p>
<p><strong>The problem</strong></p>
<p>I want to take a string, and then encrypt it using a password. The result should be a Base64 encoded string that I can store somewhere relatively safe.</p>
<pre class="brush: c#">
            // The message to encrypt.
            string Msg = &quot;This world is round, not flat, don&#039;t believe them!&quot;;
            string Password = &quot;secret&quot;;

            string EncryptedString = EncryptString(Msg, Password);
            string DecryptedString = DecryptString(EncryptedString, Password);

            Console.WriteLine(&quot;Message: {0}&quot;,Msg);
            Console.WriteLine(&quot;Password: {0}&quot;,Password);
            Console.WriteLine(&quot;Encrypted string: {0}&quot;,EncryptedString);
            Console.WriteLine(&quot;Decrypted string: {0}&quot;,DecryptedString);
</pre>
<p>In the EncryptString function we apply the TripleDES algorithm with a 128 bit key. But first we need to turn the above passphrase (&#8216;secret&#8217;) into a 128 bit key.  One useful coincidence is that the MD5 hash algorithm accepts a set of bytes of any length and turns them into a 128 bit hash. So by running the password through the MD5 hashing algorithm we create our key.</p>
<pre class="brush: c#">
            // Step 1. We hash the passphrase using MD5
            // We use the MD5 hash generator as the result is a 128 bit byte array
            // which is a valid length for the TripleDES encoder we use below

            MD5CryptoServiceProvider HashProvider = new MD5CryptoServiceProvider();
            byte[] TDESKey = HashProvider.ComputeHash(UTF8.GetBytes(Passphrase));
</pre>
<p>The TripleDES algorithm itself turns a byte array into an encrypted  byte array. So we first need to convert our C# message string (which is Unicode encoded) into a byte array  through the System.Text.UTF8Encoding encoder.</p>
<p>The key is used to initialize the TripleDES algorithm. In addition we need to specify that we will only encode something once (CipherMode.ECB) and because its unlikely that our source string fits into a single TripleDES block we need to specify how we want to pad any remaining bytes (PaddingMode.PKCS7).</p>
<pre class="brush: c#">
            // Step 2. Create a new TripleDESCryptoServiceProvider object
            TripleDESCryptoServiceProvider TDESAlgorithm = new TripleDESCryptoServiceProvider();

            // Step 3. Setup the encoder
            TDESAlgorithm.Key = TDESKey;
            TDESAlgorithm.Mode = CipherMode.ECB;
            TDESAlgorithm.Padding = PaddingMode.PKCS7;
</pre>
<p>The encrypted byte array is finally converted into a Base64 encoded string for easy storage. The <em>DecryptString</em> function is very similar to the encryption function, except that it turns the Base64 encoded encrypted message back into the original UTF8 string.</p>
<p><strong>Drawbacks to the above method</strong></p>
<p>To keep the code above straightforward we made use of the fact that an MD5 hash is exactly 128 bits in length. The C# TripleDES code accepts three possible key lengths: 64 bit, 128 bit and 192 bit. Only 192 bit keys are truly TripleDES, the 128 bit key length we obtain from the MD5 hash is only sufficient for Double DES. According to Wikipedia, that would make its real key strength only equivalent to 80 bits.</p>
<p><strong>The Source code</strong></p>
<pre class="brush: c#">
using System;
using System.Text;
using System.Security.Cryptography;

namespace EncryptStringSample
{
    class MainClass
    {

        public static string EncryptString(string Message, string Passphrase)
        {
            byte[] Results;
            System.Text.UTF8Encoding UTF8 = new System.Text.UTF8Encoding();

            // Step 1. We hash the passphrase using MD5
            // We use the MD5 hash generator as the result is a 128 bit byte array
            // which is a valid length for the TripleDES encoder we use below

            MD5CryptoServiceProvider HashProvider = new MD5CryptoServiceProvider();
            byte[] TDESKey = HashProvider.ComputeHash(UTF8.GetBytes(Passphrase));

            // Step 2. Create a new TripleDESCryptoServiceProvider object
            TripleDESCryptoServiceProvider TDESAlgorithm = new TripleDESCryptoServiceProvider();

            // Step 3. Setup the encoder
            TDESAlgorithm.Key = TDESKey;
            TDESAlgorithm.Mode = CipherMode.ECB;
            TDESAlgorithm.Padding = PaddingMode.PKCS7;

            // Step 4. Convert the input string to a byte[]
            byte[] DataToEncrypt = UTF8.GetBytes(Message);

            // Step 5. Attempt to encrypt the string
            try
            {
                ICryptoTransform Encryptor = TDESAlgorithm.CreateEncryptor();
                Results = Encryptor.TransformFinalBlock(DataToEncrypt, 0, DataToEncrypt.Length);
            }
            finally
            {
                // Clear the TripleDes and Hashprovider services of any sensitive information
                TDESAlgorithm.Clear();
                HashProvider.Clear();
            }

            // Step 6. Return the encrypted string as a base64 encoded string
            return Convert.ToBase64String(Results);
        }

        public static string DecryptString(string Message, string Passphrase)
        {
            byte[] Results;
            System.Text.UTF8Encoding UTF8 = new System.Text.UTF8Encoding();

            // Step 1. We hash the passphrase using MD5
            // We use the MD5 hash generator as the result is a 128 bit byte array
            // which is a valid length for the TripleDES encoder we use below

            MD5CryptoServiceProvider HashProvider = new MD5CryptoServiceProvider();
            byte[] TDESKey = HashProvider.ComputeHash(UTF8.GetBytes(Passphrase));

            // Step 2. Create a new TripleDESCryptoServiceProvider object
            TripleDESCryptoServiceProvider TDESAlgorithm = new TripleDESCryptoServiceProvider();

            // Step 3. Setup the decoder
            TDESAlgorithm.Key = TDESKey;
            TDESAlgorithm.Mode = CipherMode.ECB;
            TDESAlgorithm.Padding = PaddingMode.PKCS7;

            // Step 4. Convert the input string to a byte[]
            byte[] DataToDecrypt = Convert.FromBase64String(Message);

            // Step 5. Attempt to decrypt the string
            try
            {
                ICryptoTransform Decryptor = TDESAlgorithm.CreateDecryptor();
                Results = Decryptor.TransformFinalBlock(DataToDecrypt, 0, DataToDecrypt.Length);
            }
            finally
            {
                // Clear the TripleDes and Hashprovider services of any sensitive information
                TDESAlgorithm.Clear();
                HashProvider.Clear();
            }

            // Step 6. Return the decrypted string in UTF8 format
            return UTF8.GetString( Results );
        }

        public static void Main(string[] args)
        {
            // The message to encrypt.
            string Msg = &quot;This world is round, not flat, don&#039;t believe them!&quot;;
            string Password = &quot;secret&quot;;

            string EncryptedString = EncryptString(Msg, Password);
            string DecryptedString = DecryptString(EncryptedString, Password);

            Console.WriteLine(&quot;Message: {0}&quot;,Msg);
            Console.WriteLine(&quot;Password: {0}&quot;,Password);
            Console.WriteLine(&quot;Encrypted string: {0}&quot;,EncryptedString);
            Console.WriteLine(&quot;Decrypted string: {0}&quot;,DecryptedString);
        }
    }
}
</pre>
<p>This is a post from <a href="http://www.dijksterhuis.org">Martijn's C# Coding Blog</a>. </p>
]]></content:encoded>
			<wfw:commentRss>http://www.dijksterhuis.org/encrypting-decrypting-string/feed/</wfw:commentRss>
		<slash:comments>13</slash:comments>
		</item>
	</channel>
</rss>

