Notes for 2008-11(GetRange, backup,file hash, PostRequest, QueryString)
1、List<T>泛型中并没有实现ICloneable接口,也就是没有实出Clone方法,所以我们在克隆一个List时可以使用GetRange方法来代替它。
List<int> oldList = new List();
oldList.Add(1);
oldList.Add(2);
List<int> newList = oldList.GetRange(0,oldList.Count);
oldList.Add(1);
oldList.Add(2);
List<int> newList = oldList.GetRange(0,oldList.Count);
2、 backup数据库
BACKUP DATABASE ProfileDB TO DISK = 'D:\FULL_DATA\ProfileDB.bak'
WITH checksum, INIT, NOUNLOAD, NAME=N'ProfileDB Full backup', SKIP, STATS = 10, NOFORMAT
WITH checksum, INIT, NOUNLOAD, NAME=N'ProfileDB Full backup', SKIP, STATS = 10, NOFORMAT
3、计算文件的Hash值:
protected void Page_Load(object sender, EventArgs e)
{
string filePath = Request.PhysicalPath;
string hash = string.Empty;
using (FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read))
{
using (MD5 md5 = MD5.Create())
{
byte[] hashData = md5.ComputeHash(fs);
hash = ConvertToHexString(hashData);
md5.Clear();
}
fs.Close();
}
Response.Write(hash);
}
private static string ConvertToHexString(byte[] bytes)
{
int length = bytes.Length;
StringBuilder sb = new StringBuilder();
foreach (byte data in bytes)
{
sb.Append(data.ToString("x2"));
}
return sb.ToString();
}
{
string filePath = Request.PhysicalPath;
string hash = string.Empty;
using (FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read))
{
using (MD5 md5 = MD5.Create())
{
byte[] hashData = md5.ComputeHash(fs);
hash = ConvertToHexString(hashData);
md5.Clear();
}
fs.Close();
}
Response.Write(hash);
}
private static string ConvertToHexString(byte[] bytes)
{
int length = bytes.Length;
StringBuilder sb = new StringBuilder();
foreach (byte data in bytes)
{
sb.Append(data.ToString("x2"));
}
return sb.ToString();
}
hash结果都是以32个字符来表示的16进制串,通过对每位招行ToString("x2")实现。
4、封装对某一页面Post和Get操作。
/// <summary>
/// 通过Post和Get方式请求页面
/// </summary>
/// <param name="url">需要Post到的页面url</param>
/// <param name="postData">post数据的字典</param>
/// <param name="queryData">get查询的字典</param>
/// <param name="timeout">超时时间(毫秒)</param>
/// <returns>请求后的返回</returns>
public static string RequestUrl(string url, IDictionary<string, string> postData, IDictionary<string, string> queryData, int timeout)
{
//参数验证
if (url.IndexOfAny(new char[] { '?', '&' }) > -1)
throw new ArgumentException("url不应该带参数");
if (!url.StartsWith("http://"))
throw new ArgumentException("url必须以\"http://\"开头");
if (postData == null)
postData = new Dictionary<string, string>();
if (queryData == null)
queryData = new Dictionary<string, string>();
//构造url
StringBuilder urlBuilder = new StringBuilder();
foreach (var kv in queryData)
{
urlBuilder.Append(string.Format(CultureInfo.InvariantCulture, "{0}={1}&", kv.Key, HttpUtility.UrlEncode(kv.Value)));
}
string suffix = urlBuilder.Length > 0 ? ("?" + urlBuilder.ToString().TrimEnd('&')) : "";
string postUrl = url + suffix;
//构造Post数据
StringBuilder dataBuilder = new StringBuilder();
foreach (var kv in postData)
{
dataBuilder.Append(string.Format(CultureInfo.InvariantCulture, "{0}={1}&", kv.Key, kv.Value));
}
string data = dataBuilder.Length > 0 ? dataBuilder.ToString().TrimEnd('&') : "";
byte[] dataBytes = Encoding.UTF8.GetBytes(data);
//发出请求
string content = string.Empty;
//HttpWebRequest
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(postUrl);
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = dataBytes.Length;
request.Timeout = timeout;
try
{
//把dataBytes写入HttpWebRequest
using (Stream requestStream = request.GetRequestStream())
{
requestStream.Write(dataBytes, 0, dataBytes.Length);
requestStream.Close();
}
//获取HttpWebResponse
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
{
if (response.StatusCode == HttpStatusCode.OK)
{
using (Stream stream = response.GetResponseStream())
{
using (StreamReader reader = new StreamReader(stream, Encoding.UTF8))
{
content = reader.ReadToEnd();
reader.Close();
}
stream.Close();
}
}
response.Close();
}
}
catch (System.Net.WebException) { }
finally
{
if (request != null)
{
request.Abort();
request = null;
}
}
return content;
}
/// 通过Post和Get方式请求页面
/// </summary>
/// <param name="url">需要Post到的页面url</param>
/// <param name="postData">post数据的字典</param>
/// <param name="queryData">get查询的字典</param>
/// <param name="timeout">超时时间(毫秒)</param>
/// <returns>请求后的返回</returns>
public static string RequestUrl(string url, IDictionary<string, string> postData, IDictionary<string, string> queryData, int timeout)
{
//参数验证
if (url.IndexOfAny(new char[] { '?', '&' }) > -1)
throw new ArgumentException("url不应该带参数");
if (!url.StartsWith("http://"))
throw new ArgumentException("url必须以\"http://\"开头");
if (postData == null)
postData = new Dictionary<string, string>();
if (queryData == null)
queryData = new Dictionary<string, string>();
//构造url
StringBuilder urlBuilder = new StringBuilder();
foreach (var kv in queryData)
{
urlBuilder.Append(string.Format(CultureInfo.InvariantCulture, "{0}={1}&", kv.Key, HttpUtility.UrlEncode(kv.Value)));
}
string suffix = urlBuilder.Length > 0 ? ("?" + urlBuilder.ToString().TrimEnd('&')) : "";
string postUrl = url + suffix;
//构造Post数据
StringBuilder dataBuilder = new StringBuilder();
foreach (var kv in postData)
{
dataBuilder.Append(string.Format(CultureInfo.InvariantCulture, "{0}={1}&", kv.Key, kv.Value));
}
string data = dataBuilder.Length > 0 ? dataBuilder.ToString().TrimEnd('&') : "";
byte[] dataBytes = Encoding.UTF8.GetBytes(data);
//发出请求
string content = string.Empty;
//HttpWebRequest
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(postUrl);
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = dataBytes.Length;
request.Timeout = timeout;
try
{
//把dataBytes写入HttpWebRequest
using (Stream requestStream = request.GetRequestStream())
{
requestStream.Write(dataBytes, 0, dataBytes.Length);
requestStream.Close();
}
//获取HttpWebResponse
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
{
if (response.StatusCode == HttpStatusCode.OK)
{
using (Stream stream = response.GetResponseStream())
{
using (StreamReader reader = new StreamReader(stream, Encoding.UTF8))
{
content = reader.ReadToEnd();
reader.Close();
}
stream.Close();
}
}
response.Close();
}
}
catch (System.Net.WebException) { }
finally
{
if (request != null)
{
request.Abort();
request = null;
}
}
return content;
}
5、Request.QueryString里对查询字符串强制进行了一次UrlDecode,但如何使用Request["id"]方式获取查询值时则需要手工进行一次UrlDecode