C#でURLデコードするコードを紹介します。
URLデコードをする場合は、HttpUtility クラスの UrlDecodeメソッドを利用します。
HttpUtility.UrlDecode( [変換する文字列] )
変換結果は、UrlDecode メソッドの戻り値として返ります。
下図のフォームを作成します。テキストボックスを2つ、ボタンを1つ配置します。
下記コードを記述します。ButtonのClickイベントを実装しています。
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Web;
namespace URLDecodeDemo
{
public partial class FormMain : Form
{
public FormMain()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
textBox2.Text = HttpUtility.UrlDecode(textBox1.Text);
}
}
}
ボタンをクリックすると、以下のコードを実行します。上部のテキストボックスに入力された値をURLエンコードして、下部のテキストボックスに変換結果を表示します。
textBox2.Text = HttpUtility.UrlDecode(textBox1.Text);
プロジェクトを実行します。下図のウィンドウが表示されます。
上部のテキストボックスにURLエンコードされた文字列を入力します。
[button1]をクリックします。上部のテキストボックスに入力した文字がURLデコードされ、結果が下部のテキストボックスに表示されます。
C#でURLのエンコードが実行できました。
上記のコードでのURLデコードはマルチバイト文字列はUTF-8でエンコードされた文字列としてデコードします。
そのため、Shift-JISでURLエンコードした文字列を入力した場合は正しくでコードできません。
下図はShift-JISでURLエンコードされた文字列をでコードした結果です。
エンコーディングを指定して、URLでコードをする場合は、UrlDecode
メソッドの第二引数に利用するエンコーディングの System.Text.Encoding
クラスを与えます。
Shift-JISででコードする場合は次のコードになります。
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Web;
namespace URLDecodeDemo
{
public partial class FormMain : Form
{
public FormMain()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
textBox2.Text = HttpUtility.UrlDecode(textBox1.Text, System.Text.Encoding.GetEncoding("Shift-JIS"));
}
}
}
Shift-JISでURLエンコードされた文字列を入力して[button1]をクリックします。正しくデコードできることが確認できます。