.NET运行时中是否有一个类可以让我轻松处理查询字符串。
我想要以下功能:
是否有一个处理此问题的课程?
答案 0 :(得分:0)
.NET基类库没有提供任何处理查询字符串的功能,它只是将它们视为通用名称值集合。最好的办法是编写自己的扩展方法或在网上找到一些。例如:http://www.charlesrcook.com/archive/2008/07/23/c-extension-methods-for-asp.net-query-string-operations.aspx
来自CharlesRCook.com的代码:public static class Extensions
{
public static string WriteLocalPathWithQuery(
this NameValueCollection collection, Uri Url)
{
if (collection.Count == 0)
return Url.LocalPath;
StringBuilder sb = new StringBuilder(Url.LocalPath);
sb.Append("?");
for (int i = 0; i < collection.Keys.Count; i++)
{
if (i != 0)
sb.Append("&");
sb.Append(
String.Format("{0}={1}",
collection.Keys[i], collection[i])
);
}
return sb.ToString();
}
public static NameValueCollection ChangeField(this NameValueCollection collection,
string Key, string Value)
{
return ChangeField(collection, Key, Value, true);
}
public static NameValueCollection ChangeField(this NameValueCollection collection,
string Key, string Value, bool Allow)
{
if (Allow)
{
if (!String.IsNullOrEmpty(collection[Key]))
collection[Key] = Value;
else
collection.Add(Key, Value);
}
else //remove the value all together
{
if (!String.IsNullOrEmpty(collection[Key]))
collection.Remove(Key);
}
return collection;
}
public static NameValueCollection Duplicate(this NameValueCollection source)
{
NameValueCollection collection = new NameValueCollection();
foreach (string key in source)
collection.Add(key, source[key]);
return collection;
}
}