[C# Helper]
Index Books FAQ Contact About Rod
[Beginning Database Design Solutions, Second Edition]

[Beginning Software Engineering, Second Edition]

[Essential Algorithms, Second Edition]

[The Modern C# Challenge]

[WPF 3d, Three-Dimensional Graphics with WPF and C#]

[The C# Helper Top 100]

[Interview Puzzles Dissected]

[C# 24-Hour Trainer]

[C# 5.0 Programmer's Reference]

[MCSD Certification Toolkit (Exam 70-483): Programming in C#]

Title: Make string extensions to URL encode and decode strings in C#

[Make string extensions to URL encode and decode strings in C#]
When you URL encode a string, you convert special characters into numeric sequences thath are safe to use in a URL. When you URL decode a string, you reverse the process.

The following code creates extension methods for the string class that lets you convert spaces into the string " " and that URL encode and decode strings.

static class StringExtensions { // Extension to replace spaces with   public static string SpaceToNbsp(this string s) { return s.Replace(" ", " "); } // Url encode an ASCII string. public static string UrlEncode(this string s) { return HttpUtility.UrlEncode(s); } // Url decode an ASCII string. public static string UrlDecode(this string s) { return HttpUtility.UrlDecode(s); } }

The SpaceToNbsp method simply replaces spaces with the string " ". The UrlEncode and UrlDecode methods use the HttpUtility class's UrlEncode and UrlDecode methods. Those methods replace special characters with URL-safe sequences.

The string extension methods are really easy to use. This example uses them in the following code.

private void btnConvert_Click(object sender, EventArgs e) { txtNbsp.Text = txtString.Text.SpaceToNbsp(); txtUrlEncode.Text = txtString.Text.UrlEncode(); txtUrlDecode.Text = txtUrlEncode.Text.UrlDecode(); }

Download the example to experiment with it and to see additional details.

© 2009-2023 Rocky Mountain Computer Consulting, Inc. All rights reserved.