天天看點

Asp.Net常用方法

using System;

using System.Collections.Generic;

using System.Text;

using System.Text.RegularExpressions;

using System.IO;

using System.Net;

using System.Configuration;

using System.Web;

namespace Common

{

    public class Utils

    {

        #region 系統版本

        /// <summary>

        /// 版本資訊類

        /// </summary>

        public class VersionInfo

        {

            public int FileMajorPart

            {

                get { return 2; }

            }

            public int FileMinorPart

                get { return 1; }

            public int FileBuildPart

                get { return 0; }

            public string ProductName

                get { return "DTcms"; }

            public int ProductType

        }

        #endregion

        #region 對象轉換處理

        /// 判斷對象是否為Int32類型的數字

        /// <param name="Expression"></param>

        /// <returns></returns>

        public static bool IsNumeric(object expression)

            if (expression != null)

                return IsNumeric(expression.ToString());

            return false;

        public static bool IsNumeric(string expression)

                string str = expression;

                if (str.Length > 0 && str.Length <= 11 && Regex.IsMatch(str, @"^[-]?[0-9]*[.]?[0-9]*$"))

                {

                    if ((str.Length < 10) || (str.Length == 10 && str[0] == '1') || (str.Length == 11 && str[0] == '-' && str[1] == '1'))

                        return true;

                }

        /// 是否為Double類型

        /// <param name="expression"></param>

        public static bool IsDouble(object expression)

                return Regex.IsMatch(expression.ToString(), @"^([0-9])[0-9]*(\.\w*)?$");

        /// 将字元串轉換為數組

        /// <param name="str">字元串</param>

        /// <returns>字元串數組</returns>

        public static string[] GetStrArray(string str)

            return str.Split(new char[',']);

        /// 将數組轉換為字元串

        /// <param name="list">List</param>

        /// <param name="speater">分隔符</param>

        /// <returns>String</returns>

        public static string GetArrayStr(List<string> list, string speater)

            StringBuilder sb = new StringBuilder();

            for (int i = 0; i < list.Count; i++)

                if (i == list.Count - 1)

                    sb.Append(list[i]);

                else

                    sb.Append(speater);

            return sb.ToString();

        /// object型轉換為bool型

        /// <param name="strValue">要轉換的字元串</param>

        /// <param name="defValue">預設值</param>

        /// <returns>轉換後的bool類型結果</returns>

        public static bool StrToBool(object expression, bool defValue)

                return StrToBool(expression, defValue);

            return defValue;

        /// string型轉換為bool型

        public static bool StrToBool(string expression, bool defValue)

                if (string.Compare(expression, "true", true) == 0)

                    return true;

                else if (string.Compare(expression, "false", true) == 0)

                    return false;

        /// 将對象轉換為Int32類型

        /// <param name="expression">要轉換的字元串</param>

        /// <returns>轉換後的int類型結果</returns>

        public static int ObjToInt(object expression, int defValue)

                return StrToInt(expression.ToString(), defValue);

        /// 将字元串轉換為Int32類型

        public static int StrToInt(string expression, int defValue)

            if (string.IsNullOrEmpty(expression) || expression.Trim().Length >= 11 || !Regex.IsMatch(expression.Trim(), @"^([-]|[0-9])[0-9]*(\.\w*)?$"))

                return defValue;

            int rv;

            if (Int32.TryParse(expression, out rv))

                return rv;

            return Convert.ToInt32(StrToFloat(expression, defValue));

        /// Object型轉換為decimal型

        /// <returns>轉換後的decimal類型結果</returns>

        public static decimal ObjToDecimal(object expression, decimal defValue)

                return StrToDecimal(expression.ToString(), defValue);

        /// string型轉換為decimal型

        public static decimal StrToDecimal(string expression, decimal defValue)

            if ((expression == null) || (expression.Length > 10))

            decimal intValue = defValue;

                bool IsDecimal = Regex.IsMatch(expression, @"^([-]|[0-9])[0-9]*(\.\w*)?$");

                if (IsDecimal)

                    decimal.TryParse(expression, out intValue);

            return intValue;

        /// Object型轉換為float型

        public static float ObjToFloat(object expression, float defValue)

                return StrToFloat(expression.ToString(), defValue);

        /// string型轉換為float型

        public static float StrToFloat(string expression, float defValue)

            float intValue = defValue;

                bool IsFloat = Regex.IsMatch(expression, @"^([-]|[0-9])[0-9]*(\.\w*)?$");

                if (IsFloat)

                    float.TryParse(expression, out intValue);

        /// 将對象轉換為日期時間類型

        /// <param name="str">要轉換的字元串</param>

        public static DateTime StrToDateTime(string str, DateTime defValue)

            if (!string.IsNullOrEmpty(str))

                DateTime dateTime;

                if (DateTime.TryParse(str, out dateTime))

                    return dateTime;

        public static DateTime StrToDateTime(string str)

            return StrToDateTime(str, DateTime.Now);

        /// <param name="obj">要轉換的對象</param>

        public static DateTime ObjectToDateTime(object obj)

            return StrToDateTime(obj.ToString());

        public static DateTime ObjectToDateTime(object obj, DateTime defValue)

            return StrToDateTime(obj.ToString(), defValue);

        /// 将對象轉換為字元串

        /// <returns>轉換後的string類型結果</returns>

        public static string ObjectToStr(object obj)

            if (obj == null)

                return "";

            return obj.ToString().Trim();

        #region 分割字元串

        /// 分割字元串

        public static string[] SplitString(string strContent, string strSplit)

            if (!string.IsNullOrEmpty(strContent))

                if (strContent.IndexOf(strSplit) < 0)

                    return new string[] { strContent };

                return Regex.Split(strContent, Regex.Escape(strSplit), RegexOptions.IgnoreCase);

            else

                return new string[0] { };

        public static string[] SplitString(string strContent, string strSplit, int count)

            string[] result = new string[count];

            string[] splited = SplitString(strContent, strSplit);

            for (int i = 0; i < count; i++)

                if (i < splited.Length)

                    result[i] = splited[i];

                    result[i] = string.Empty;

            return result;

        #region 删除最後結尾的一個逗号

        /// 删除最後結尾的一個逗号

        public static string DelLastComma(string str)

            return str.Substring(0, str.LastIndexOf(","));

        #region 删除最後結尾的指定字元後的字元

        /// 删除最後結尾的指定字元後的字元

        public static string DelLastChar(string str, string strchar)

            if (string.IsNullOrEmpty(str))

            if (str.LastIndexOf(strchar) >= 0 && str.LastIndexOf(strchar) == str.Length - 1)

                return str.Substring(0, str.LastIndexOf(strchar));

            return str;

        #region 生成指定長度的字元串

        /// 生成指定長度的字元串,即生成strLong個str字元串

        /// <param name="strLong">生成的長度</param>

        /// <param name="str">以str生成字元串</param>

        public static string StringOfChar(int strLong, string str)

            string ReturnStr = "";

            for (int i = 0; i < strLong; i++)

                ReturnStr += str;

            return ReturnStr;

        #region 生成日期随機碼

        /// 生成日期随機碼

        public static string GetRamCode()

            #region

            return DateTime.Now.ToString("yyyyMMddHHmmssffff");

            #endregion

        #region 生成随機字母或數字

        /// 生成随機數字

        /// <param name="length">生成長度</param>

        public static string Number(int Length)

            return Number(Length, false);

        /// <param name="Length">生成長度</param>

        /// <param name="Sleep">是否要在生成前将目前線程阻止以避免重複</param>

        public static string Number(int Length, bool Sleep)

            if (Sleep)

                System.Threading.Thread.Sleep(3);

            string result = "";

            System.Random random = new Random();

            for (int i = 0; i < Length; i++)

                result += random.Next(10).ToString();

        /// 生成随機字母字元串(數字字母混和)

        /// <param name="codeCount">待生成的位數</param>

        public static string GetCheckCode(int codeCount)

            string str = string.Empty;

            int rep = 0;

            long num2 = DateTime.Now.Ticks + rep;

            rep++;

            Random random = new Random(((int)(((ulong)num2) & 0xffffffffL)) | ((int)(num2 >> rep)));

            for (int i = 0; i < codeCount; i++)

                char ch;

                int num = random.Next();

                if ((num % 2) == 0)

                    ch = (char)(0x30 + ((ushort)(num % 10)));

                    ch = (char)(0x41 + ((ushort)(num % 0x1a)));

                str = str + ch.ToString();

        /// 根據日期和随機碼生成訂單号

        public static string GetOrderNumber()

            string num = DateTime.Now.ToString("yyMMddHHmmss");//yyyyMMddHHmmssms

            return num + Number(2).ToString();

        private static int Next(int numSeeds, int length)

            byte[] buffer = new byte[length];

            System.Security.Cryptography.RNGCryptoServiceProvider Gen = new System.Security.Cryptography.RNGCryptoServiceProvider();

            Gen.GetBytes(buffer);

            uint randomResult = 0x0;//這裡用uint作為生成的随機數  

            for (int i = 0; i < length; i++)

                randomResult |= ((uint)buffer[i] << ((length - 1 - i) * 8));

            return (int)(randomResult % numSeeds);

        #region 截取字元長度

        /// 截取字元長度

        /// <param name="inputString">字元</param>

        /// <param name="len">長度</param>

        public static string CutString(string inputString, int len)

            if (string.IsNullOrEmpty(inputString))

            inputString = DropHTML(inputString);

            ASCIIEncoding ascii = new ASCIIEncoding();

            int tempLen = 0;

            string tempString = "";

            byte[] s = ascii.GetBytes(inputString);

            for (int i = 0; i < s.Length; i++)

                if ((int)s[i] == 63)

                    tempLen += 2;

                    tempLen += 1;

                try

                    tempString += inputString.Substring(i, 1);

                catch

                    break;

                if (tempLen > len)

            //如果截過則加上半個省略号 

            byte[] mybyte = System.Text.Encoding.Default.GetBytes(inputString);

            if (mybyte.Length > len)

                tempString += "…";

            return tempString;

        #region 清除HTML标記

        public static string DropHTML(string Htmlstring)

            if (string.IsNullOrEmpty(Htmlstring)) return "";

            //删除腳本  

            Htmlstring = Regex.Replace(Htmlstring, @"<script[^>]*?>.*?</script>", "", RegexOptions.IgnoreCase);

            //删除HTML  

            Htmlstring = Regex.Replace(Htmlstring, @"<(.[^>]*)>", "", RegexOptions.IgnoreCase);

            Htmlstring = Regex.Replace(Htmlstring, @"([\r\n])[\s]+", "", RegexOptions.IgnoreCase);

            Htmlstring = Regex.Replace(Htmlstring, @"-->", "", RegexOptions.IgnoreCase);

            Htmlstring = Regex.Replace(Htmlstring, @"<!--.*", "", RegexOptions.IgnoreCase);

            Htmlstring = Regex.Replace(Htmlstring, @"&(quot|#34);", "\"", RegexOptions.IgnoreCase);

            Htmlstring = Regex.Replace(Htmlstring, @"&(amp|#38);", "&", RegexOptions.IgnoreCase);

            Htmlstring = Regex.Replace(Htmlstring, @"&(lt|#60);", "<", RegexOptions.IgnoreCase);

            Htmlstring = Regex.Replace(Htmlstring, @"&(gt|#62);", ">", RegexOptions.IgnoreCase);

            Htmlstring = Regex.Replace(Htmlstring, @"&(nbsp|#160);", " ", RegexOptions.IgnoreCase);

            Htmlstring = Regex.Replace(Htmlstring, @"&(iexcl|#161);", "\xa1", RegexOptions.IgnoreCase);

            Htmlstring = Regex.Replace(Htmlstring, @"&(cent|#162);", "\xa2", RegexOptions.IgnoreCase);

            Htmlstring = Regex.Replace(Htmlstring, @"&(pound|#163);", "\xa3", RegexOptions.IgnoreCase);

            Htmlstring = Regex.Replace(Htmlstring, @"&(copy|#169);", "\xa9", RegexOptions.IgnoreCase);

            Htmlstring = Regex.Replace(Htmlstring, @"&#(\d+);", "", RegexOptions.IgnoreCase);

            Htmlstring.Replace("<", "");

            Htmlstring.Replace(">", "");

            Htmlstring.Replace("\r\n", "");

            Htmlstring = HttpContext.Current.Server.HtmlEncode(Htmlstring).Trim();

            return Htmlstring;

        #region 清除HTML标記且傳回相應的長度

        public static string DropHTML(string Htmlstring, int strLen)

            return CutString(DropHTML(Htmlstring), strLen);

        #region TXT代碼轉換成HTML格式

        /// 字元串字元處理

        /// <param name="chr">等待處理的字元串</param>

        /// <returns>處理後的字元串</returns>

        /// //把TXT代碼轉換成HTML格式

        public static String ToHtml(string Input)

            StringBuilder sb = new StringBuilder(Input);

            sb.Replace("&", "&");

            sb.Replace("<", "<");

            sb.Replace(">", ">");

            sb.Replace("\r\n", "<br />");

            sb.Replace("\n", "<br />");

            sb.Replace("\t", " ");

            //sb.Replace(" ", " ");

        #region HTML代碼轉換成TXT格式

        /// //把HTML代碼轉換成TXT格式

        public static String ToTxt(String Input)

            sb.Replace(" ", " ");

            sb.Replace("<br>", "\r\n");

            sb.Replace("<br>", "\n");

            sb.Replace("<br />", "\n");

            sb.Replace("<br />", "\r\n");

            sb.Replace("<", "<");

            sb.Replace(">", ">");

            sb.Replace("&", "&");

        #region 檢測是否有Sql危險字元

        /// 檢測是否有Sql危險字元

        /// <param name="str">要判斷字元串</param>

        /// <returns>判斷結果</returns>

        public static bool IsSafeSqlString(string str)

            return !Regex.IsMatch(str, @"[-|;|,|\/|\(|\)|\[|\]|\}|\{|%|@|\*|!|\']");

        /// 檢查危險字元

        /// <param name="Input"></param>

        public static string Filter(string sInput)

            if (sInput == null || sInput == "")

                return null;

            string sInput1 = sInput.ToLower();

            string output = sInput;

            string pattern = @"*|and|exec|insert|select|delete|update|count|master|truncate|declare|char(|mid(|chr(|'";

            if (Regex.Match(sInput1, Regex.Escape(pattern), RegexOptions.Compiled | RegexOptions.IgnoreCase).Success)

                throw new Exception("字元串中含有非法字元!");

                output = output.Replace("'", "''");

            return output;

        /// <summary> 

        /// 檢查過濾設定的危險字元

        /// </summary> 

        /// <param name="InText">要過濾的字元串 </param> 

        /// <returns>如果參數存在不安全字元,則傳回true </returns> 

        public static bool SqlFilter(string word, string InText)

            if (InText == null)

                return false;

            foreach (string i in word.Split('|'))

                if ((InText.ToLower().IndexOf(i + " ") > -1) || (InText.ToLower().IndexOf(" " + i) > -1))

        #region 過濾特殊字元

        /// 過濾特殊字元

        public static string Htmls(string Input)

            if (Input != string.Empty && Input != null)

                string ihtml = Input.ToLower();

                ihtml = ihtml.Replace("<script", "<script");

                ihtml = ihtml.Replace("script>", "script>");

                ihtml = ihtml.Replace("<%", "<%");

                ihtml = ihtml.Replace("%>", "%>");

                ihtml = ihtml.Replace("<$", "<$");

                ihtml = ihtml.Replace("$>", "$>");

                return ihtml;

                return string.Empty;

        #region 檢查是否為IP位址

        /// 是否為ip

        /// <param name="ip"></param>

        public static bool IsIP(string ip)

            return Regex.IsMatch(ip, @"^((2[0-4]\d|25[0-5]|[01]?\d\d?)\.){3}(2[0-4]\d|25[0-5]|[01]?\d\d?)$");

        #region 獲得目前絕對路徑

        /// 獲得目前絕對路徑

        /// <param name="strPath">指定的路徑</param>

        /// <returns>絕對路徑</returns>

        public static string GetMapPath(string strPath)

            if (strPath.ToLower().StartsWith("http://"))

                return strPath;

            if (HttpContext.Current != null)

                return HttpContext.Current.Server.MapPath(strPath);

            else //非web程式引用

                strPath = strPath.Replace("/", "\\");

                if (strPath.StartsWith("\\"))

                    strPath = strPath.Substring(strPath.IndexOf('\\', 1)).TrimStart('\\');

                return System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, strPath);

        #region 檔案操作

        /// 删除單個檔案

        /// <param name="_filepath">檔案相對路徑</param>

        public static bool DeleteFile(string _filepath)

            if (string.IsNullOrEmpty(_filepath))

            string fullpath = GetMapPath(_filepath);

            if (File.Exists(fullpath))

                File.Delete(fullpath);

                return true;

        /// 删除上傳的檔案(及縮略圖)

        /// <param name="_filepath"></param>

        public static void DeleteUpFile(string _filepath)

                return;

            string fullpath = GetMapPath(_filepath); //原圖

            if (_filepath.LastIndexOf("/") >= 0)

                string thumbnailpath = _filepath.Substring(0, _filepath.LastIndexOf("/")) + "mall_" + _filepath.Substring(_filepath.LastIndexOf("/") + 1);

                string fullTPATH = GetMapPath(thumbnailpath); //宿略圖

                if (File.Exists(fullTPATH))

                    File.Delete(fullTPATH);

        /// 傳回檔案大小KB

        /// <returns>int</returns>

        public static int GetFileSize(string _filepath)

                return 0;

                FileInfo fileInfo = new FileInfo(fullpath);

                return ((int)fileInfo.Length) / 1024;

            return 0;

        /// 傳回檔案擴充名,不含“.”

        /// <param name="_filepath">檔案全名稱</param>

        /// <returns>string</returns>

        public static string GetFileExt(string _filepath)

            if (_filepath.LastIndexOf(".") > 0)

                return _filepath.Substring(_filepath.LastIndexOf(".") + 1); //檔案擴充名,不含“.”

            return "";

        /// 傳回檔案名,不含路徑

        public static string GetFileName(string _filepath)

            return _filepath.Substring(_filepath.LastIndexOf(@"/") + 1);

        /// 檔案是否存在

        /// <returns>bool</returns>

        public static bool FileExists(string _filepath)

        #region 讀取或寫入cookie

        /// 寫cookie值

        /// <param name="strName">名稱</param>

        /// <param name="strValue">值</param>

        public static void WriteCookie(string strName, string strValue)

            HttpCookie cookie = HttpContext.Current.Request.Cookies[strName];

            if (cookie == null)

                cookie = new HttpCookie(strName);

            cookie.Value = UrlEncode(strValue);

            HttpContext.Current.Response.AppendCookie(cookie);

        public static void WriteCookie(string strName, string key, string strValue)

            cookie[key] = UrlEncode(strValue);

        public static void WriteCookie(string strName, string key, string strValue, int expires)

            cookie.Expires = DateTime.Now.AddMinutes(expires);

        /// <param name="strValue">過期時間(分鐘)</param>

        public static void WriteCookie(string strName, string strValue, int expires)

        /// 讀cookie值

        /// <returns>cookie值</returns>

        public static string GetCookie(string strName)

            if (HttpContext.Current.Request.Cookies != null && HttpContext.Current.Request.Cookies[strName] != null)

                return UrlDecode(HttpContext.Current.Request.Cookies[strName].Value.ToString());

        public static string GetCookie(string strName, string key)

            if (HttpContext.Current.Request.Cookies != null && HttpContext.Current.Request.Cookies[strName] != null && HttpContext.Current.Request.Cookies[strName][key] != null)

                return UrlDecode(HttpContext.Current.Request.Cookies[strName][key].ToString());

        #region 替換指定的字元串

        /// 替換指定的字元串

        /// <param name="originalStr">原字元串</param>

        /// <param name="oldStr">舊字元串</param>

        /// <param name="newStr">新字元串</param>

        public static string ReplaceStr(string originalStr, string oldStr, string newStr)

            if (string.IsNullOrEmpty(oldStr))

            return originalStr.Replace(oldStr, newStr);

        #region 顯示分頁

        /// 傳回分頁頁碼

        /// <param name="pageSize">頁面大小</param>

        /// <param name="pageIndex">目前頁</param>

        /// <param name="totalCount">總記錄數</param>

        /// <param name="linkUrl">連結位址,__id__代表頁碼</param>

        /// <param name="centSize">中間頁碼數量</param>

        public static string OutPageList(int pageSize, int pageIndex, int totalCount, string linkUrl, int centSize)

            //計算頁數

            if (totalCount < 1 || pageSize < 1)

            int pageCount = totalCount / pageSize;

            if (pageCount < 1)

            if (totalCount % pageSize > 0)

                pageCount += 1;

            if (pageCount <= 1)

            StringBuilder pageStr = new StringBuilder();

            string pageId = "__id__";

            string firstBtn = "<a href=\"" + ReplaceStr(linkUrl, pageId, (pageIndex - 1).ToString()) + "\">上一頁</a>";

            string lastBtn = "<a href=\"" + ReplaceStr(linkUrl, pageId, (pageIndex + 1).ToString()) + "\">下一頁</a>";

            string firstStr = "<a href=\"" + ReplaceStr(linkUrl, pageId, "1") + "\">1</a>";

            string lastStr = "<a href=\"" + ReplaceStr(linkUrl, pageId, pageCount.ToString()) + "\">" + pageCount.ToString() + "</a>";

            if (pageIndex <= 1)

                firstBtn = "<span class=\"disabled\">上一頁</span>";

            if (pageIndex >= pageCount)

                lastBtn = "<span class=\"disabled\">下一頁</span>";

            if (pageIndex == 1)

                firstStr = "<span class=\"current\">1</span>";

            if (pageIndex == pageCount)

                lastStr = "<span class=\"current\">" + pageCount.ToString() + "</span>";

            int firstNum = pageIndex - (centSize / 2); //中間開始的頁碼

            if (pageIndex < centSize)

                firstNum = 2;

            int lastNum = pageIndex + centSize - ((centSize / 2) + 1); //中間結束的頁碼

            if (lastNum >= pageCount)

                lastNum = pageCount - 1;

            pageStr.Append(firstBtn + firstStr);

            if (pageIndex >= centSize)

                pageStr.Append("<span>...</span>\n");

            for (int i = firstNum; i <= lastNum; i++)

                if (i == pageIndex)

                    pageStr.Append("<span class=\"current\">" + i + "</span>");

                    pageStr.Append("<a href=\"" + ReplaceStr(linkUrl, pageId, i.ToString()) + "\">" + i + "</a>");

            if (pageCount - pageIndex > centSize - ((centSize / 2)))

                pageStr.Append("<span>...</span>");

            pageStr.Append(lastStr + lastBtn);

            return pageStr.ToString();

        #region URL處理

        /// URL字元編碼

        public static string UrlEncode(string str)

            str = str.Replace("'", "");

            return HttpContext.Current.Server.UrlEncode(str);

        /// URL字元解碼

        public static string UrlDecode(string str)

            return HttpContext.Current.Server.UrlDecode(str);

        /// 組合URL參數

        /// <param name="_url">頁面位址</param>

        /// <param name="_keys">參數名稱</param>

        /// <param name="_values">參數值</param>

        public static string CombUrlTxt(string _url, string _keys, params string[] _values)

            StringBuilder urlParams = new StringBuilder();

            try

                string[] keyArr = _keys.Split(new char[] { '&' });

                for (int i = 0; i < keyArr.Length; i++)

                    if (!string.IsNullOrEmpty(_values[i]) && _values[i] != "0")

                    {

                        _values[i] = UrlEncode(_values[i]);

                        urlParams.Append(string.Format(keyArr[i], _values) + "&");

                    }

                if (!string.IsNullOrEmpty(urlParams.ToString()) && _url.IndexOf("?") == -1)

                    urlParams.Insert(0, "?");

            catch

                return _url;

            return _url + DelLastChar(urlParams.ToString(), "&");

        #region URL請求資料

        /// HTTP POST方式請求資料

        /// <param name="url">URL.</param>

        /// <param name="param">POST的資料</param>

        public static string HttpPost(string url, string param)

            System.Net.ServicePointManager.Expect100Continue = false;

            HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url);

            request.Method = "POST";

            request.ContentType = "application/x-www-form-urlencoded";

            request.Accept = "*/*";

            request.Timeout = 15000;

            request.AllowAutoRedirect = false;

            StreamWriter requestStream = null;

            WebResponse response = null;

            string responseStr = null;

                requestStream = new StreamWriter(request.GetRequestStream());

                requestStream.Write(param);

                requestStream.Close();

                response = request.GetResponse();

                if (response != null)

                    StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8);

                    responseStr = reader.ReadToEnd();

                    reader.Close();

            catch (Exception)

                throw;

            finally

                request = null;

                requestStream = null;

                response = null;

            return responseStr;

        /// HTTP GET方式請求資料.

        public static string HttpGet(string url)

            ServicePointManager.ServerCertificateValidationCallback =

                    delegate { return true; };

            request.Method = "GET";

            //request.ContentType = "application/x-www-form-urlencoded";

        /// 執行URL擷取頁面内容

        public static string UrlExecute(string urlPath)

            if (string.IsNullOrEmpty(urlPath))

                return "error";

            StringWriter sw = new StringWriter();

                HttpContext.Current.Server.Execute(urlPath, sw);

                return sw.ToString();

                sw.Close();

                sw.Dispose();

    }

}

繼續閱讀