使用WebUtility.UrlEncode时,输入字符串的格式不正确

时间:2013-12-09 20:01:05

标签: c#

我从WebUtility得到一个例外,我不确定为什么(虽然我怀疑这是一个简单的事情,我的咖啡因剥夺了大脑的缺失)。文档声明它期望UTF-8,所以我做了转换但仍然没有爱:

Unhandled Exception: System.FormatException: Input string was not in a correct format.
   at System.Text.StringBuilder.AppendFormat(IFormatProvider provider, String format, Object[] args)
   at System.String.Format(IFormatProvider provider, String format, Object[] args)
   at System.IO.TextWriter.WriteLine(String format, Object arg0)
   at System.IO.TextWriter.SyncTextWriter.WriteLine(String format, Object arg0)
   at System.Console.WriteLine(String format, Object arg0)
   at testApp.Program.Main(String[] args) in c:\Users\roberth\Programming_Projects\VisualStudio\testApp\testApp\Program.cs:line 18

以下是一个示例程序:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net;    

namespace testApp
{
    class Program
    {
        static void Main(string[] args)
        {         
            String url = "This is a URL to Encode%!";
            Byte[] bytes = Encoding.Default.GetBytes(url.ToCharArray());
            String utfUrl = Encoding.UTF8.GetString(bytes);

            Console.WriteLine(utfUrl);
            Console.WriteLine("Encoded: {}", WebUtility.UrlEncode(utfUrl));
            Console.WriteLine("Decoded: {}", WebUtility.UrlDecode(utfUrl));
        }
    }
}

1 个答案:

答案 0 :(得分:5)

您在0来电中缺少Console.WriteLine(格式字符串参数的索引):

Console.WriteLine("Encoded: {0}", WebUtility.UrlEncode(utfUrl));
Console.WriteLine("Decoded: {0}", WebUtility.UrlDecode(utfUrl));

来自MSDN

  

格式项的语法是{index[,alignment][:formatString]},   指定强制索引,可选长度和对齐方式   格式化文本的格式,以及格式说明符的可选字符串   控制相应对象值的方式的字符   格式化。