• C# 很久以前几个常用类


    Base64加密解密

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    
    namespace 沃狐新浪博客推广系统
    {
        class Base64
        {
            /// <summary>     
            /// 将字符串使用base64算法加密    
            /// </summary>   
            ///  <param name="code_type">编码类型(编码名称)   
            ///  * 代码页 名称     
            ///  * 1200 "UTF-16LE"、"utf-16"、"ucs-2"、"unicode"或"ISO-10646-UCS-2"    
            ///  * 1201 "UTF-16BE"或"unicodeFFFE"    
            ///  * 1252 "windows-1252"  
            ///  * 65000 "utf-7"、"csUnicode11UTF7"、"unicode-1-1-utf-7"、"unicode-2-0-utf-7"、"x-unicode-1-1-utf-7"或"x-unicode-2-0-utf-7"    
            ///  * 65001 "utf-8"、"unicode-1-1-utf-8"、"unicode-2-0-utf-8"、"x-unicode-1-1-utf-8"或"x-unicode-2-0-utf-8"   
            ///  * 20127 "us-ascii"、"us"、"ascii"、"ANSI_X3.4-1968"、"ANSI_X3.4-1986"、"cp367"、"csASCII"、"IBM367"、"iso-ir-6"、"ISO646-US"或"ISO_646.irv:1991"     
            ///  * 54936 "GB18030"        /// </param>     /// <param name="code">待加密的字符串</param>    
            ///  <returns>加密后的字符串</returns>    
             public string EncodeBase64(string code_type, string code)    
            {         
                 string encode = "";         
                 byte[] bytes = Encoding.GetEncoding(code_type).GetBytes(code); 
                //将一组字符编码为一个字节序列.        
                 try        
                 {            
                 encode = Convert.ToBase64String(bytes); 
                     //将8位无符号整数数组的子集转换为其等效的,以64为基的数字编码的字符串形式.         
                 }         catch        
                 {             
                     encode = code;     
                 }        
                 return encode;   
             }
            /// <summary>     
            /// 将字符串使用base64算法解密    
            /// </summary>   
            /// <param name="code_type">编码类型</param>   
            /// <param name="code">已用base64算法加密的字符串</param>   
            /// <returns>解密后的字符串</returns>     
            public string DecodeBase64(string code_type, string code)  
            {        
                string decode = "";      
                byte[] bytes = Convert.FromBase64String(code);  //将2进制编码转换为8位无符号整数数组.        
                try      
                {      
                    decode = Encoding.GetEncoding(code_type).GetString(bytes);  //将指定字节数组中的一个字节序列解码为一个字符串。 
                }         
                catch      
                {        
                    decode = code;    
                }       
                return decode;   
            }
    
        }
    }
    View Code

    BitmapRegion绘制图形控件

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Drawing;
    using System.Drawing.Drawing2D;
    using System.Windows.Forms;
    namespace 沃狐新浪博客推广系统
    {
        class BitmapRegion
        {
            public BitmapRegion()
            {
            }
    
            /// <summary>
            /// Create and apply the region on the supplied control
            /// </summary>
            /// The Control object to apply the region to//
            /// The Bitmap object to create the region from
            public void CreateControlRegion(Control control, Bitmap bitmap)
            {
                // Return if control and bitmap are null
                if (control == null || bitmap == null)
                    return;
    
                // Set our control's size to be the same as the bitmap
                control.Width = bitmap.Width;
                control.Height = bitmap.Height;
    
                // Check if we are dealing with Form here
                if (control is System.Windows.Forms.Form)
                {
                    // Cast to a Form object
                    Form form = (Form)control;
    
                    // Set our form's size to be a little larger that the bitmap just 
                    // in case the form's border style is not set to none in the first place
                    form.Width += 15;
                    form.Height += 35;
    
                    // No border
                    form.FormBorderStyle = FormBorderStyle.None;
    
                    // Set bitmap as the background image
                    form.BackgroundImage = bitmap;
    
                    // Calculate the graphics path based on the bitmap supplied
                    GraphicsPath graphicsPath = CalculateControlGraphicsPath(bitmap);
    
                    // Apply new region
                    form.Region = new Region(graphicsPath);
                }
    
               // Check if we are dealing with Button here
                else if (control is System.Windows.Forms.Button)
                {
                    // Cast to a button object
                    Button button = (Button)control;
    
                    // Do not show button text
                    button.Text = "";
    
                    // Change cursor to hand when over button
                    button.Cursor = Cursors.Hand;
    
                    // Set background image of button
                    button.BackgroundImage = bitmap;
    
                    // Calculate the graphics path based on the bitmap supplied
                    GraphicsPath graphicsPath = CalculateControlGraphicsPath(bitmap);
    
                    // Apply new region
                    button.Region = new Region(graphicsPath);
                }
            }
    
            /// <summary>
            /// Calculate the graphics path that representing the figure in the bitmap 
            /// excluding the transparent color which is the top left pixel.
            /// </summary>
            /// The Bitmap object to calculate our graphics path from
            /// <returns>Calculated graphics path</returns>
            private static GraphicsPath CalculateControlGraphicsPath(Bitmap bitmap)
            {
                // Create GraphicsPath for our bitmap calculation
                GraphicsPath graphicsPath = new GraphicsPath();
    
                // Use the top left pixel as our transparent color
                Color colorTransparent = bitmap.GetPixel(0, 0);
    
                // This is to store the column value where an opaque pixel is first found.
                // This value will determine where we start scanning for trailing opaque pixels.
                int colOpaquePixel = 0;
    
                // Go through all rows (Y axis)
                for (int row = 0; row < bitmap.Height; row++)
                {
                    // Reset value
                    colOpaquePixel = 0;
    
                    // Go through all columns (X axis)
                    for (int col = 0; col < bitmap.Width; col++)
                    {
                        // If this is an opaque pixel, mark it and search for anymore trailing behind
                        if (bitmap.GetPixel(col, row) != colorTransparent)
                        {
                            // Opaque pixel found, mark current position
                            colOpaquePixel = col;
    
                            // Create another variable to set the current pixel position
                            int colNext = col;
    
                            // Starting from current found opaque pixel, search for anymore opaque pixels 
                            // trailing behind, until a transparent pixel is found or minimum width is reached
                            for (colNext = colOpaquePixel; colNext < bitmap.Width; colNext++)
                                if (bitmap.GetPixel(colNext, row) == colorTransparent)
                                    break;
    
                            // Form a rectangle for line of opaque pixels found and add it to our graphics path
                            graphicsPath.AddRectangle(new Rectangle(colOpaquePixel, row, colNext - colOpaquePixel, 1));
    
                            // No need to scan the line of opaque pixels just found
                            col = colNext;
                        }
                    }
                }
    
                // Return calculated graphics path
                return graphicsPath;
            }
        }
    }
    View Code

    CatchUrls抓取网页url

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Xml;
    using System.Net;
    using System.IO;
    using System.Collections;
    using System.Text.RegularExpressions;
    namespace 沃狐新浪博客推广系统
    {
        class CatchUrls
        {
            string strCode;
            ArrayList alLinks;
            // 获取指定网页的HTML代码
            private string url = "";
            public string URL
           {
                get
                {
                    return url;
                }
                set
                {
                    url = value;
                }
            }
            public string htmlCode;
            public  string GetPageSource()
            {
                Uri uri = new Uri(URL);
                // http:// blog.sina.com.cn/lm/oldrank/20120615/all.html
                HttpWebRequest hwReq = (HttpWebRequest)WebRequest.Create(uri);
                HttpWebResponse hwRes = (HttpWebResponse)hwReq.GetResponse();
                hwReq.Method = "Get";
                hwReq.KeepAlive = false;
                StreamReader reader = new StreamReader(hwRes.GetResponseStream(), System.Text.Encoding.GetEncoding("GB2312"));
                return reader.ReadToEnd();
            }
            // 提取HTML代码中的网址 
            public  ArrayList GetHyperLinks()
            {
                ArrayList al = new ArrayList();
                string strRegex = @"http://([w-]+.)+[w-]+(/[w- ./?%&=]*)?";
                Regex r = new Regex(strRegex, RegexOptions.IgnoreCase);
                MatchCollection m = r.Matches(htmlCode);
                //progressBar1.Maximum = m.Count;
                for (int i = 0; i <= m.Count - 1; i++)
                {
                    bool rep = false;
                    string strNew = m[i].ToString();
                    // 过滤重复的URL 
                    foreach (string str in al)
                    {
                        if (strNew == str)
                        {
                            rep = true;
                            break;
                        }
                    }
                    if (!rep)
                    {
    
                        if (strNew.IndexOf("blog.sina.com.cn/u") >= 0)
                        {
                            strNew = strNew.Replace("http://blog.sina.com.cn/u/", "");
                            al.Add(strNew.Trim());
                        }
                    }
                }
                al.Sort();//重新排序
                return al;
            }
            //
            static string GetURLContent(string url, string EncodingType)
            {
                string PetiResp = "";
                Stream mystream;
                System.Net.HttpWebRequest req = (System.Net.HttpWebRequest)System.Net.HttpWebRequest.Create(url);
                req.AllowAutoRedirect = true;
                System.Net.HttpWebResponse resp = (System.Net.HttpWebResponse)req.GetResponse();
                if (resp.StatusCode == System.Net.HttpStatusCode.OK)
                {
                    mystream = resp.GetResponseStream();
                    System.Text.Encoding encode = System.Text.Encoding.GetEncoding(EncodingType);
                    StreamReader readStream = new StreamReader(mystream, encode);
                    char[] cCont = new char[500];
                    int count = readStream.Read(cCont, 0, 256);
                    while (count > 0)
                    {
                        // Dumps the 256 characters on a string and displays the string to the console.
                        String str = new String(cCont, 0, count);
                        PetiResp += str;
                        count = readStream.Read(cCont, 0, 256);
                    }
                    resp.Close();
                    return PetiResp;
                }
                resp.Close();
                return null;
            }
            // 获取网址的域名后缀 
            static string GetDomain(string strURL)
            {
                string retVal;
                string strRegex = @"(.com/|.net/|.cn/|.org/|.gov/|.cn/)";
                Regex r = new Regex(strRegex, RegexOptions.IgnoreCase);
                Match m = r.Match(strURL);
                retVal = m.ToString();
                strRegex = @".|/$";
                retVal = Regex.Replace(retVal, strRegex, "").ToString();
                if (retVal == "")
                    retVal = "other";
                return retVal;
            }
            //public string BaseURLs;
           
        }
    }
    View Code

    CookieComputer提取post模拟登陆网站cookie.cs

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    
    using System.Net;
    using System.Web;
    using System.IO;
    using System.Collections; 
    namespace 沃狐新浪博客推广系统
    {
        class CookieComputer
        {
            #region 通过登录获取cookie信息参数
            //登录链接
            private static string url = "";
            /// <summary>
            /// 登录基URL,默认为空
            /// </summary>
            public static string Url
            {
                get
                {
                    return url;
                }
                set
                {
                    url = value;
                }
            }
            //用户名
          
            private static string username = "";
            /// <summary>
            /// 登录用户名,默认为空
            /// </summary>
            public static string Username
            {
                get
                {
                    return username;
                }
                set
                {
                    username = value;
                }
            }
            //密码
            private static string password = "";
            /// <summary>
            /// 登录密码,默认为空
            /// </summary>
            public static string Password
            {
                get
                {
                    return password;
                }
                set
                {
                    password = value;
                }
            }
    
           
            //表单需要提交的参数,注意改为你已注册的信息。
             private static string postDate="";
             /// <summary>
             /// 表单需要提交的参数,注意改为你已注册的信息。
             /// </summary>
             public static string PostDate
             {
                 get
                 {
                     return postDate;
                 }
                 set
                 {
                     postDate = value;
                 }
             }
    
            #endregion
    
            //写成无参数方便线程调用
            /// <summary>
            /// 获取目标网站cookie
            /// </summary>
            /// <returns>CookieContainer</returns>
            public static CookieContainer Get_SinaLogin()
            {
                //新建cookie容器
                CookieContainer CookiC = new CookieContainer();
                //处理表单的绝对URL地址
                string FormURL = Url;
                //表单需要提交的参数,注意改为你已注册的信息。
                // "username=" + Username + "&password=" + Password;
                string FormData = PostDate;
                //设定编码格式
                Encoding encoding = Encoding.UTF8;
                //将编码转换成字节数组
                byte[] data = encoding.GetBytes(FormData);
                //创建HttpWebRequest请求
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(FormURL);
                ///<!--设定标头开始-->
                //数据提交方式
                request.Method = "POST";
                //设定请求连接类型
                request.ContentType = "application/x-www-form-urlencoded";
                //设定请求内容长度
                request.ContentLength = data.Length;
                //声明了浏览器用于 HTTP 请求的用户代理头的值
                request.UserAgent = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 1.1.4322)";
                ///<!--设定标头结束-->
                //返回请求数据流
                Stream newStream = request.GetRequestStream();
                //向当前流中写入字节序列
                newStream.Write(data, 0, data.Length);
                //关闭流
                newStream.Close();
                //获取或设置与此请求关联的 cookie。
                request.CookieContainer = CookiC;
                //返回来自 Internet 资源的响应。
                HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                //将返回的cookie添加进cookie容器
                CookiC.Add(response.Cookies);
                //获取流,该流用于读取来自服务器的响应的体。
                Stream stream = response.GetResponseStream();
                //将流转换成指定编码格式字符串
                string WebContent = new StreamReader(stream, System.Text.Encoding.UTF8).ReadToEnd();
                //返回获取到的cookie
                return CookiC;
            }
            /// <summary>
            /// 获取目标网站cookie
            /// </summary>
            /// <returns>CookieContainer</returns>
            public static CookieContainer Get_ssoSinaLogin()
            {
                //新建cookie容器
                CookieContainer CookiC = new CookieContainer();
                //处理表单的绝对URL地址
                string FormURL = Url;
                //表单需要提交的参数,注意改为你已注册的信息。
                // "entry=blog&reg_entry=blog&reference=http://blog.sina.com.cn&door=&safe_login=1&username=" + Username + "&password=" + Password;
                string FormData = PostDate;
                //设定编码格式
                Encoding encoding = Encoding.UTF8;
                //将编码转换成字节数组
                byte[] data = encoding.GetBytes(FormData);
                //创建HttpWebRequest请求
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(FormURL);
                ///<!--设定标头开始-->
                //数据提交方式
                request.Method = "POST";
                //设定请求连接类型
                request.ContentType = "application/x-www-form-urlencoded";
                request.Accept = "text/html, application/xhtml+xml, */*";
                request.KeepAlive = true;
                //设定请求内容长度
                request.ContentLength = data.Length;
                //声明了浏览器用于 HTTP 请求的用户代理头的值
                request.UserAgent = " Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0; 360SE)";
                ///<!--设定标头结束-->
                //返回请求数据流
                Stream newStream = request.GetRequestStream();
                //向当前流中写入字节序列
                newStream.Write(data, 0, data.Length);
                //关闭流
                newStream.Close();
                //获取或设置与此请求关联的 cookie。
                request.CookieContainer = CookiC;
                //返回来自 Internet 资源的响应。
                HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                //将返回的cookie添加进cookie容器
                CookiC.Add(response.Cookies);
                //获取流,该流用于读取来自服务器的响应的体。
                Stream stream = response.GetResponseStream();
                //将流转换成指定编码格式字符串
                string WebContent = new StreamReader(stream, System.Text.Encoding.UTF8).ReadToEnd();
                //返回获取到的cookie
                return CookiC;
            }
    
            /// <summary>
            /// 遍历CookieContainer提取cookie
            /// </summary>
            /// <param name="cc">需要遍历的CookieContainer</param>
            /// <returns>List<Cookie></returns>
            public static List<Cookie> GetAllCookies(CookieContainer cc)
            {
                List<Cookie> lstCookies = new List<Cookie>();
                Hashtable table = (Hashtable)cc.GetType().InvokeMember("m_domainTable", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.GetField | System.Reflection.BindingFlags.Instance, null, cc, new object[] { });
                foreach (object pathList in table.Values)
                {
                    SortedList lstCookieCol = (SortedList)pathList.GetType().InvokeMember("m_list", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.GetField | System.Reflection.BindingFlags.Instance, null, pathList, new object[] { });
                    foreach (CookieCollection colCookies in lstCookieCol.Values)
                        foreach (Cookie c in colCookies) lstCookies.Add(c);
                }
                return lstCookies;
            } 
        }
    }
    View Code

    INIClass专门ini操作类

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Runtime.InteropServices;
    using System.IO;
    namespace 沃狐新浪博客推广系统
    {
        class INIClass
        {
            public string inipath;
            [DllImport("kernel32")]
            private static extern long WritePrivateProfileString(string section, string key, string val, string filePath);
            [DllImport("kernel32")]
            private static extern int GetPrivateProfileString(string section, string key, string def, StringBuilder retVal, int size, string filePath);
            [DllImport("kernel32")]
            private static extern long WritePrivateProfileSection(string section, string val, string filePath);
            [DllImport("kernel32")]
            private static extern int GetPrivateProfileString(string section, string key, string def, Byte[] retVal, int size, string filePath);
            /// <summary>
            /// 构造方法
            /// </summary>
            /// <param name="INIPath">文件路径</param>
            public INIClass(string INIPath)
            {
                inipath = INIPath;
                if (inipath == null || inipath.Length < 1 || !ExistINIFile)
                {
                    File.Create(INIPath).Close();
                }
            }
    
            /// <summary>
            /// 写入INI文件
            /// </summary>
            /// <param name="Section">项目名称(如 [TypeName] )</param>
            /// <param name="Key"></param>
            /// <param name="Value"></param>
            public void IniWriteValue(string Section, string Key, object objValue)
            {
                if (objValue == null) objValue = "";
                WritePrivateProfileString(Section, Key, objValue.ToString().Trim(), this.inipath);
            }
            /// <summary>
            /// 写入INI文件,没有健只有值
            /// </summary>
            /// <param name="Section">项目名称(如 [TypeName] )</param>
            /// <param name="Value"></param> 
            public void IniWriteSection(string section, string val)
            {
                WritePrivateProfileSection(section, val, this.inipath);
            }
            /// <summary>
            /// 读出INI文件
            /// </summary>
            /// <param name="Section">项目名称(如 [TypeName] )</param>
            /// <param name="Key"></param>
            public string IniReadValue(string Section, string Key)
            {
                StringBuilder temp = new StringBuilder(500);
                int i = GetPrivateProfileString(Section, Key, "", temp, 500, this.inipath);
                return temp.ToString();
            }
            /// <summary>
            /// 读出INI文件数组
            /// </summary>
            /// <param name="Section">项目名称(如 [TypeName] )</param>
            /// <param name="Key"></param>
            public byte[] IniReadValueNew(string Section, string Key)
            {
                byte[] temp = new byte[500];
                int i = GetPrivateProfileString(Section, Key, "", temp, 500, this.inipath);
                return temp;
            }
            /// <summary>
            /// 验证文件是否存在
            /// </summary>
            /// <returns>布尔值</returns>
            public bool ExistINIFile
            {
                get { 
                    return File.Exists(inipath); 
                }
            }
        }
    }
    View Code

    Sendwall新浪发送信息类

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    
    using System.Net;
    using System.Web;
    using System.IO;
    using System.Windows.Forms;
    using System.Text.RegularExpressions;
    using System.Runtime.InteropServices;
    namespace 沃狐新浪博客推广系统
    {
        class Sendwall
        {
    
          private  string tuid="";
            public string Tuid
            {
                get
                {
                    return tuid;
                }
                set
                {
                    tuid = value;
                }
            }
          private   string fuid="";
            public string Fuid
            {
                get
                {
                    return fuid;
                }
                set
                {
                    fuid = value;
                }
            }
            private   string content="";
            public string Content
            {
                get
                {
                    return content;
                }
                set
                {
                    content = value;
                }
            }
            CookieContainer cc = new CookieContainer();
            public CookieContainer Cc
            {
                get
                {
                    return cc;
                }
                set
                {
                    cc = value;
                }
            }
            private Form1  m_spiderForm;
            /// <summary>
            ///蜘蛛报告其结果的对象。
            /// </summary>此处最难理解
            public Form1 ReportTo
            {
                get
                {
                    return m_spiderForm;
                }
    
                set
                {
                    m_spiderForm = value;
                }
            }
            //转换成URlEncode
            public string UrlEncode(string str)
            {
                StringBuilder sb = new StringBuilder();
                byte[] byStr = System.Text.Encoding.UTF8.GetBytes(str); //默认是System.Text.Encoding.Default.GetBytes(str)
                for (int i = 0; i < byStr.Length; i++)
                {
                    sb.Append(@"%" + Convert.ToString(byStr[i], 16));
                }
    
                return (sb.ToString());
            }
            //Form1 frm1 = new Form1();
            //发纸条目前无法判断是否发生成功
            public void SendwallF()
            {
                string FormData = "version=7";
                FormData += "&varname=addFriendRequest";
                FormData += "&tuid=" + Tuid;//自己
                FormData += "&rnd=1342799242793" ;
                FormData += "&fuid=" + fuid;//对方
                FormData += "&content=" + UrlEncode(Content);
                FormData += "&authcode=";
               //http://control.blog.sina.com.cn/riaapi/profile/messagesend.php?tuid=2823833972&fuid=2774260630&authcode=3281&content=%E4%BD%A0%E5%A5%BD&varname=addFriendRequest&version=7&rnd=1342799242793
                string FormURL = "http://control.blog.sina.com.cn/riaapi/profile/messagesend.php";
                //try
                //{
                    HttpWebRequest Myrequest = (HttpWebRequest)WebRequest.Create(FormURL + FormData);
                    Myrequest.CookieContainer = Cc;
                    Myrequest.Timeout = 3000;
                    Myrequest.ContentType = "application/x-www-form-urlencoded";
                    Myrequest.UserAgent = "Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0; 360SE)";
                    Myrequest.Accept = "application/javascript, */*;q=0.8";
                    Myrequest.Headers.Add("Accept-Language", "zh-CN");
                    //
                    Myrequest.Headers.Add("Accept-Encoding", "gzip, deflate");
                    //
                    Myrequest.Headers.Add("Cache-Control", "no-cache");
    
                    Myrequest.Referer = "http://blog.sina.com.cn/s/profile_" + fuid + ".html";
                    HttpWebResponse Myresponse = (HttpWebResponse)Myrequest.GetResponse();
                    cc.Add(Myresponse.Cookies);
                    Stream Mystream = Myresponse.GetResponseStream();
                    string WebContent = new StreamReader(Mystream, Encoding.GetEncoding("utf-8")).ReadToEnd();
                    Myresponse.Close();
                    Mystream.Close();
    
                    ReportTo.SetrichTextWithDelegate(ReportTo.richTextBox1, "发送纸条:" + WebContent + "成功");
                    ReportTo.autoEventStartF.Reset();
                //}
                //catch 
                //{ 
                //    frm1.SetrichTextWithDelegate(frm1.richTextBox1, "发送纸条失败");
                //}
                //string WebContent = new StreamReader(Mystream, Encoding.GetEncoding("utf-8")).ReadToEnd();
                //Match m = Regex.Match(WebContent, @"{""rows""([^}]*)}", RegexOptions.IgnoreCase);
                //return true;
            }
            //发送留言
            public void SendmsgF()
            {
                //try
                //{
                    //请求参数设定
                    string FormData = "domain=1";
                    //
                    FormData += "&uid=" + Tuid;
                    //
                    FormData += "&msg=" + Content;
                    //
                    string FormURL = "http://control.blog.sina.com.cn/blog_rebuild/riaapi/profile/note/notewalladd.php";
                    //
                    Encoding encoding = Encoding.UTF8;
                    //
                    byte[] data = encoding.GetBytes(FormData);
                    //
                    HttpWebRequest request = (HttpWebRequest)WebRequest.Create(FormURL);
                    //
                    request.Method = "POST";
                    //数据提交方式
                    request.ContentType = "application/x-www-form-urlencoded";
    
                    //
                    request.KeepAlive = true;
                    //
                    request.AllowWriteStreamBuffering = true;
                    //
                    request.Credentials = System.Net.CredentialCache.DefaultCredentials;
                    //
                    request.MaximumResponseHeadersLength = -1;
                    //
                    request.Referer = "http://blog.sina.com.cn/u/" + Tuid;
                    //
                    request.Accept = "text/html, application/xhtml+xml, */*";
                    //
                    request.UserAgent = "Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0)";
                    //
                    request.Headers.Add("Accept-Language", "zh-CN");
                    //
                    request.Headers.Add("Accept-Encoding", "gzip, deflate");
                    //
                    request.Headers.Add("Cache-Control", "no-cache");
                    //
                    request.CookieContainer = Cc;
                    //
                    request.ContentLength = data.Length;
                    //模拟一个UserAgent
                    Stream newStream = request.GetRequestStream();
                    //
                    newStream.Write(data, 0, data.Length);
                    //
                    newStream.Close();
                    //
                    HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                    //
                    request.GetResponse().ResponseUri.ToString();
                    //
                    Stream stream = response.GetResponseStream();
                    //
                    string WebContent = new StreamReader(stream, System.Text.Encoding.UTF8).ReadToEnd();
                    //
               
                    Match m = Regex.Match(WebContent, @"{""rows""([^}]*)}", RegexOptions.IgnoreCase);
                    //
                    ReportTo.SetrichTextWithDelegate(ReportTo.richTextBox1, "发送留言成功");
                    ReportTo.autoEventStartF.Reset();
                //if (m.Success)
                //{
                //    string str = m.Value.Replace("rows", "");
                //    str = str.Replace(":", "");
                //    //str = str.Replace("{", "");
                //    //str = str.Replace("}", "");
                //    if (str.Length > 3)
                //    {
                //        return true;
                //    }
                //    else
                //    {
                //        return false;
                //    }
                //}
                //else
                //{
                //    return false;
                //}
                //}
                //catch { return false; }
            }
            //加好友
            public void SendaddFriendF()
            {
                string FormData = "version=7";
                FormData += "&varname=addFriendRequest";
                FormData += "&tuid=" + Tuid;
                FormData += "&rnd=";
                FormData += "&fuid=" + fuid;
                FormData += "&content=" + UrlEncode(Content);
                FormData += "&authcode=";
                //try
                //{
                string FormURL = "http://control.blog.sina.com.cn/riaapi/profile/invitesend.php";
                HttpWebRequest Myrequest = (HttpWebRequest)WebRequest.Create(FormURL + FormData);
                Myrequest.CookieContainer = Cc;
                HttpWebResponse Myresponse = (HttpWebResponse)Myrequest.GetResponse();
                cc.Add(Myresponse.Cookies);
                Stream Mystream = Myresponse.GetResponseStream();
                //return true;
                //}
                //catch { return false; }
                ReportTo.autoEventStartF.Reset();
            }
            //加关注
            public void SendattentionF()
            {
                Random rd = new Random();
                string FormData = "varname=requestId_"+rd.Next().ToString();;
                FormData += "&uid=" + fuid;
                FormData += "&aid=" + Tuid;
                string FormURL = "http://control.blog.sina.com.cn/riaapi/profile/attention_add.php";
                //try
                //{
                HttpWebRequest Myrequest = (HttpWebRequest)WebRequest.Create(FormURL + FormData);
                Myrequest.CookieContainer = Cc;
                HttpWebResponse Myresponse = (HttpWebResponse)Myrequest.GetResponse();
                cc.Add(Myresponse.Cookies);
                Stream Mystream = Myresponse.GetResponseStream();
                //return true;
                //}
                //catch { return false; }
                ReportTo.autoEventStartF.Reset();
            }
        }
    }
    View Code

    xmlRW专门xml读写类

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Xml;
    
    using System.Windows.Forms;
    namespace 沃狐新浪博客推广系统
    {
        class xmlRW
        {
            
    
            public List<xmlUserLogin> Read(string path)
            {
                int UserCode = 0;
                string Auser="",UserPwd = "", UserName = "", Remark = "";
                List<xmlUserLogin> list = new List<xmlUserLogin>();
                XmlReaderSettings xmlSet = new XmlReaderSettings(); 
                        using (XmlReader reader = XmlReader.Create(path, xmlSet))
                        {
                            while (reader.Read())  //使用XmlReader对象单向高效地读取xml文件
                            {
                                    xmlUserLogin UserLogin = new xmlUserLogin();
                                    if (reader.NodeType == XmlNodeType.Element && "User" == reader.LocalName)
                                    {
                                        Auser =reader.GetAttribute(0);
                                    }
                                    if (reader.NodeType == XmlNodeType.Element && "UserCode" == reader.LocalName)
                                    {
                                        UserCode = Convert.ToInt16(reader.ReadString()); 
                                    }
                                    if (reader.NodeType == XmlNodeType.Element && "UserName" == reader.LocalName)
                                    {
                                        UserName= reader.ReadString(); 
                                    }
                                    if (reader.NodeType == XmlNodeType.Element && "UserPwd" == reader.LocalName)
                                    {
                                        UserPwd = reader.ReadString();
    
                                    }
                                    if (reader.NodeType == XmlNodeType.Element && "Remark" == reader.LocalName)
                                    {
    
                                        UserLogin.auser = Auser;
                                        UserLogin.userCode = UserCode;
                                        UserLogin.userName = UserName;
                                        UserLogin.userPwd = UserPwd;
                                        UserLogin.remark = Remark;
                                        list.Add(UserLogin);
                                    }
                                    
                                    
                          }
                    }
                return list;
            }
    
            //WriteXml 完成对User的修改密码操作    
            //FileName 当前xml文件的存放位置    
            //UserCode 欲操作用户的编码    
            //UserPassword 欲修改用户的密码
            public void UpdateNode(string FileName,  string OUserName,string NUserName, string NUserPwd,string Remark)
            {
                //初始化XML文档操作类       
                XmlDocument myDoc = new XmlDocument();       
                //加载XML文件       
                myDoc.Load(FileName);       
                //搜索指定的节点        
                System.Xml.XmlNodeList nodes = myDoc.SelectNodes("//User");       
                if (nodes != null)      
                {         
                    foreach (System.Xml.XmlNode xn in nodes)    
                    {
                        if (xn.SelectSingleNode("UserName").InnerText == OUserName)
                        {
                            xn.SelectSingleNode("UserName").InnerText = NUserName;
                            xn.SelectSingleNode("UserPwd").InnerText = NUserPwd;
                            xn.SelectSingleNode("Remark").InnerText = Remark; 
       
                        }         
                   
                    }      
                }       
                myDoc.Save(FileName);  
            }
    
            //DeleteNode 完成对User的添加操作   
            //FileName 当前xml文件的存放位置   
            //UserCode 欲添加用户的编码   
            public void DeleteNode(string FileName, string UserName)   
            {       
                //初始化XML文档操作类    
                XmlDocument myDoc = new XmlDocument();      
                //加载XML文件      
                myDoc.Load(FileName);       
                //搜索指定某列,一般是主键列    
                XmlNodeList myNode = myDoc.SelectNodes("//UserName");    
                //判断是否有这个节点      
                if (!(myNode == null))        
                {            
                    //遍历节点,找到符合条件的元素          
                    foreach (XmlNode  xn in myNode)       
                    {
                        if (xn.InnerXml == UserName)                   
                            //删除元素的父节点                  
                            xn.ParentNode.ParentNode.RemoveChild(xn.ParentNode);  
                    }        
                }      
            //保存      
            myDoc.Save(FileName);  
            }
            //WriteXml 完成对User的添加操作  
            //FileName 当前xml文件的存放位置    
            //UserCode 欲添加用户的编码   
            //UserName 欲添加用户的姓名   
            //UserPassword 欲添加用户的密码   
            public void AddNode(string FileName, string UserName, string UserPassword, string Remark) 
            {           
                //初始化XML文档操作类    
                XmlDocument myDoc = new XmlDocument();       
                //加载XML文件      
                myDoc.Load(FileName);   
                //添加元素--UserName      
                XmlElement eleUserName = myDoc.CreateElement("UserName");
                XmlText textUserName = myDoc.CreateTextNode(UserName);      
                //添加元素--UserPwd      
                XmlElement eleUserPwd = myDoc.CreateElement("UserPwd");
                XmlText textUserPwd = myDoc.CreateTextNode(UserPassword);
                //添加元素--Remark     
                XmlElement eleRemark = myDoc.CreateElement("Remark");
                XmlText textRemark = myDoc.CreateTextNode(Remark);   
                //添加节点 User要对应我们xml文件中的节点名字      
                XmlNode newElem = myDoc.CreateNode(XmlNodeType.Element, "User","");
    
                XmlAttribute newElemAttrib =null;
                newElemAttrib = myDoc.CreateAttribute("eb");
                newElemAttrib.Value = "true";
                newElem.Attributes.Append(newElemAttrib);
                //newElem.Attributes
                //newElem = myDoc.CreateNode(XmlNodeType.Attribute, "eb", "true");
                //在节点中添加元素        
                newElem.AppendChild(eleUserName);
                newElem.LastChild.AppendChild(textUserName);
    
                newElem.AppendChild(eleUserPwd);
                newElem.LastChild.AppendChild(textUserPwd);
    
                newElem.AppendChild(eleRemark);
                newElem.LastChild.AppendChild(textRemark);    
                //将节点添加到文档中       
                XmlElement root = myDoc.DocumentElement;      
            root.AppendChild(newElem);     
            //保存       
                myDoc.Save(FileName);            }
        }
        }
    View Code

    xmlUserLogin参数类

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    
    namespace 沃狐新浪博客推广系统
    {
        class xmlUserLogin
        {
            private string Auser = "";
            private int UserCode = 0; 
            private string UserName = "";
            private string UserPwd = "";
            private string Remark = "";
            public string auser
            {
                get
                {
                    return Auser;
                }
                set
                {
                    Auser = value;
                }
            }
            public int userCode 
            { 
                get
                {
                    return UserCode; 
                } 
                set 
                {
                    UserCode = value;
                } 
            }
            public string userPwd {
                get 
                {
                    return UserPwd; 
                }
                set
                { 
                    UserPwd = value;
                } 
            }
            public string userName
            { 
                get { 
                    return UserName;
                } 
                set 
                {
                    UserName = value;
                }
            }
            public string remark { 
                get 
                { 
                    return Remark; 
                }
                set
                { 
                   Remark = value;
                } 
            }
        }
    }
    View Code

    c# 读写xml 操作类

    usingSystem;
    usingSystem.Collections.Generic;
    usingSystem.Text;
    usingSystem.Xml;
       
    namespaceKeyCalc
    {
        classXmlClass
        {
            /// <summary>
            /// 配置文件路径
            /// </summary>
            privatestringxmlFilePath;
            /// <summary>  
            /// 皮肤索引   
            /// </summary>  
            publicstringskinIndex;
            /// <summary>  
            /// 皮肤路径  
            /// </summary>  
            publicstringskinPath;
         
            publicXmlClass()
            {
                //指定XML文件名  
                xmlFilePath ="config.xml";
                //检测XML配置文件是否存在  
                if(System.IO.File.Exists(xmlFilePath))
                    return;
                CreateDefaultXml();
            }
        
            #region " ReadXML() 读取XML配置文件的参数设置,获取下载的TXT文件路径与上传的数据文件路径"  
            /// <summary>  
            /// 读取XML配置文件的参数设置,获取下载的TXT文件路径与上传的数据文件路径  
            /// </summary>  
            /// <returns></returns>  
            publicboolReadXML()
            {
                try
                {
                    XmlDocument xmlDoc=newXmlDocument();
                    //读取XML配置文件  
                    xmlDoc.Load(xmlFilePath);
         
                    //读取XML文件节点  
                    XmlNode rootNode = xmlDoc.SelectSingleNode("Skin").SelectSingleNode("ParameterSet");
                    if( rootNode==null)
                        throw(newException("XML配置文件信息异常"));
         
                    //获取XML文件参数设置下的节点值  
                    XmlElement downfile = (XmlElement)(rootNode.SelectSingleNode("SkinIndex"));
                    if(downfile ==null)
                        throw(newException("XML配置文件信息异常"));
                    skinIndex = downfile.InnerText;
                    XmlElement uploadfile = (XmlElement)(rootNode.SelectSingleNode("SkinPath"));
                    if(uploadfile ==null)
                        throw(newException("XML配置文件信息异常"));
                    skinPath = uploadfile.InnerText;
         
                    returntrue;
                }
                catch(System.Exception e)
                {
                    throw(e);
                }
            }
            #endregion
        
        
            #region " WriteXML() 写XML配置文件的参数设置,保存下载的TXT文件路径与上传的数据文件路径"  
            /// <summary>  
            /// 写XML配置文件的参数设置,保存下载的TXT文件路径与上传的数据文件路径  
            /// </summary>  
            /// <returns></returns>  
            publicboolWriteXML()
            {
                try
                {
                    XmlDocument xmlDoc =newXmlDocument();
                    //读取XML配置文件  
                    xmlDoc.Load(xmlFilePath);
         
                    //读取XML文件节点  
                    XmlNode rootNode = xmlDoc.SelectSingleNode("Skin").SelectSingleNode("ParameterSet");
                    if(rootNode ==null)
                        throw(newException("XML配置文件信息异常"));
                         
                    //设置XML文件节点的值  
                    XmlElement skinIndexs = (XmlElement)(rootNode.SelectSingleNode("SkinIndex"));
                    if(skinIndexs ==null)
                        throw(newException("XML配置文件信息异常"));
                    skinIndexs.InnerText = skinIndex;
                    XmlElement skinPaths = (XmlElement)(rootNode.SelectSingleNode("SkinPath"));
                    if(skinPaths ==null)
                        throw(newException("XML配置文件信息异常"));
                    skinPaths.InnerText = skinPath;
         
                    //保存XML文件  
                    xmlDoc.Save(xmlFilePath);
                         
                    returntrue;
                }
                catch(System.Exception ex)
                {
                    throw(ex);
                }
            }
            #endregion
        
            #region " CreateDefaultXml() 创建一个默认的XML配置文件"  
            /// <summary>  
            /// 创建一个默认的XML配置文件  
            /// </summary>  
            privatevoidCreateDefaultXml()
            {
                try
                {
                    XmlDocument xmlDoc =newXmlDocument();
                    //创建XML文件描述  
                    XmlDeclaration dec = xmlDoc.CreateXmlDeclaration("1.0","GB2312",null);
                    xmlDoc.AppendChild(dec);
                    //创建根元素  
                    XmlNode root = xmlDoc.CreateNode(XmlNodeType.Element,"Skin","");
                    xmlDoc.AppendChild(root);
         
                    //添加参数设置节点  
                    XmlNode parConfig = xmlDoc.CreateNode(XmlNodeType.Element,"ParameterSet","");
                    root.AppendChild(parConfig);
         
                    //添加下载到PDA的TXT文件路径  
                    XmlElement skinIndexs = xmlDoc.CreateElement("SkinIndex");
                    skinIndexs.InnerText ="";
                    parConfig.AppendChild(skinIndexs);
                    //添加PDA数据文件上传到PC端的文件路径  
                    XmlElement skinPaths = xmlDoc.CreateElement("SkinPath");
                    skinPaths.InnerText ="";
                    parConfig.AppendChild(skinPaths);
         
                    //保存xml文件  
                    xmlDoc.Save(xmlFilePath);  
                }
                catch(System.Exception ex)
                {
                    throw(newException("创建默认XML文件失败"+ex.Message));
                }
            }
            #endregion  
       
        }
    }
     
    View Code

    C#读写XML文件

    **************************** phone.xml ****************************
    <?xml version="1.0" encoding="utf-8" ?>
    <PhoneBook>
     <phone id="001">
      <Name>加菲尔德</Name>
      <Number>5555555</Number>
      <City>纽约</City>
      <DateOfBirth>26/10/1978</DateOfBirth>
     </phone>
     <phone id="002">
      <Name>迈克</Name>
      <Number>6666666</Number>
      <City>纽约</City>
      <DateOfBirth>12/02/1978</DateOfBirth>
     </phone>
    </PhoneBook>
    *********************************************************************
    ·使用Document读取及写入XML方法
      private void xmlfun()
      {
       XmlDocument doc = new XmlDocument();
       doc.Load(Server.MapPath("phone.xml"));
       XmlElement node = doc.CreateElement("phone");
       XmlAttribute atr = doc.CreateAttribute("id");
       atr.InnerText = "003";
       node.Attributes.Append(atr);
       XmlNode xnode = (XmlNode)doc.CreateElement("Name");
       xnode.InnerText="testName";
       node.AppendChild(xnode);
       xnode = (XmlNode)doc.CreateElement("Number");
       xnode.InnerText="119";
       node.AppendChild(xnode);
       xnode = (XmlNode)doc.CreateElement("City");
       xnode.InnerText="cs";
       node.AppendChild(xnode);
       xnode = (XmlNode)doc.CreateElement("DateOfBirth");
       xnode.InnerText="12/02/1978";
       node.AppendChild(xnode);
       doc.DocumentElement.InsertAfter(node,doc.DocumentElement.LastChild);
       doc.Save(Server.MapPath("phone1.xml"));   //必须要存为不同的文件
      }
     
    ·使用XmlTextWriter写入XML方法
      private void xmlwriter()
      {
       XmlTextWriter writer= new XmlTextWriter(Server.MapPath("phone4.xml"),null);
       writer.Formatting = Formatting.Indented;  //缩进格式
       writer.Indentation =4;
       writer.WriteStartDocument();
       writer.WriteStartElement("Person");
       writer.WriteStartAttribute("ID",null);
       writer.WriteString("004");
       writer.WriteEndAttribute();
       writer.WriteStartElement("Name");
       writer.WriteString("testWriterName");
       writer.WriteEndElement();
       writer.WriteStartElement("Number");
       writer.WriteString("88888");
       writer.WriteEndElement();
       writer.WriteStartElement("City");
       writer.WriteString("testWriterCity");
       writer.WriteEndElement();
       writer.Flush();
       writer.Close();
      }
     
    ·使用XmlTextReader读取XML方法
      private void xmlread()
      {
          XmlTextReader reader = new XmlTextReader(Server.MapPath("phone.xml"));
          while(reader.Read())
          {
              if(reader.LocalName.Equals("Name") || reader.LocalName.Equals("Number"))
          {
          this.Label1.Text += reader.ReadString()+"	";
      }
     
    ·作用SqlCommand.ExecuteXmlReader()取得XML
    SqlConnecting conn = new SqlConnection(CONNSTR);
    SqlCommand cmd = new SqlCommand("select fname from employee for xml auto",conn);
    conn.open();
    XmlReader reader = cmd.ExecuteXmlReader();
    ......
    ################ 所取xml数据格式 #################
    <employee fname="aria"/>
    <employee fname="carlors"/>......
     
    View Code

    C#读写INI文件

    摘自:伊图教程网[www.etoow.com]
    http://www.etoow.com/html/2007-08/1187271505-1.html
    
           虽然微软早已经建议在WINDOWS中用注册表代替INI文件,但是在实际应用中,INI文件仍然有用武之地,尤其现在绿色软件的流行,越来越多的程序将自己的一些配置信息保存到了INI文件中。       INI文件是文本文件,由若干节(section)组成,在每个带括号的标题下面,是若干个关键词(key)及其对应的值(Value)
      [Section]
      Key=Value
          
           VC中提供了API函数进行INI文件的读写操作,但是微软推出的C#编程语言中却没有相应的方法,下面是一个C# ini文件读写类,从网上收集的,很全,就是没有对section的改名功能,高手可以增加一个。
    
    using System;
    
    using System.IO;
    
    using System.Runtime.InteropServices;
    
    using System.Text;
    
    using System.Collections;
    
    using System.Collections.Specialized;
    
    
    
    namespace wuyisky{
    
      /**/
    
      /// <summary>
    
      /// IniFiles的类
    
      /// </summary>
    
      public class IniFiles
    
      {
    
        public string FileName; //INI文件名
    
        //声明读写INI文件的API函数
    
        [DllImport("kernel32")]
    
        private static extern bool WritePrivateProfileString(string section, string key, string val, string filePath);
    
        [DllImport("kernel32")]
    
        private static extern int GetPrivateProfileString(string section, string key, string def, byte[] retVal, int size, string filePath);
    
        //类的构造函数,传递INI文件名
    
        public IniFiles(string AFileName)
    
        {
    
          // 判断文件是否存在
    
          FileInfo fileInfo = new FileInfo(AFileName);
    
          //Todo:搞清枚举的用法
    
          if ((!fileInfo.Exists))
    
          { //|| (FileAttributes.Directory in fileInfo.Attributes))
    
            //文件不存在,建立文件
    
            System.IO.StreamWriter sw = new System.IO.StreamWriter(AFileName, false, System.Text.Encoding.Default);
    
            try
    
            {
    
              sw.Write("#表格配置档案");
    
              sw.Close();
    
            }
    
    
    
            catch
    
            {
    
              throw (new ApplicationException("Ini文件不存在"));
    
            }
    
          }
    
          //必须是完全路径,不能是相对路径
    
          FileName = fileInfo.FullName;
    
        }
    
        //写INI文件
    
        public void WriteString(string Section, string Ident, string Value)
    
        {
    
          if (!WritePrivateProfileString(Section, Ident, Value, FileName))
    
          {
    
     
    
            throw (new ApplicationException("写Ini文件出错"));
    
          }
    
        }
    
        //读取INI文件指定
    
        public string ReadString(string Section, string Ident, string Default)
    
        {
    
          Byte[] Buffer = new Byte[65535];
    
          int bufLen = GetPrivateProfileString(Section, Ident, Default, Buffer, Buffer.GetUpperBound(0), FileName);
    
          //必须设定0(系统默认的代码页)的编码方式,否则无法支持中文
    
          string s = Encoding.GetEncoding(0).GetString(Buffer);
    
          s = s.Substring(0, bufLen);
    
          return s.Trim();
    
        }
    
    
    
        //读整数
    
        public int ReadInteger(string Section, string Ident, int Default)
    
        {
    
          string intStr = ReadString(Section, Ident, Convert.ToString(Default));
    
          try
    
          {
    
            return Convert.ToInt32(intStr);
    
    
    
          }
    
          catch (Exception ex)
    
          {
    
            Console.WriteLine(ex.Message);
    
            return Default;
    
          }
    
        }
    
    
    
        //写整数
    
        public void WriteInteger(string Section, string Ident, int Value)
    
        {
    
          WriteString(Section, Ident, Value.ToString());
    
        }
    
    
    
        //读布尔
    
        public bool ReadBool(string Section, string Ident, bool Default)
    
        {
    
          try
    
          {
    
            return Convert.ToBoolean(ReadString(Section, Ident, Convert.ToString(Default)));
    
          }
    
          catch (Exception ex)
    
          {
    
            Console.WriteLine(ex.Message);
    
            return Default;
    
          }
    
        }
    
    
    
        //写Bool
    
        public void WriteBool(string Section, string Ident, bool Value)
    
        {
    
          WriteString(Section, Ident, Convert.ToString(Value));
    
        }
    
    
    
        //从Ini文件中,将指定的Section名称中的所有Ident添加到列表中
    
        public void ReadSection(string Section, StringCollection Idents)
    
        {
    
          Byte[] Buffer = new Byte[16384];
    
          //Idents.Clear();
    
    
    
          int bufLen = GetPrivateProfileString(Section, null, null, Buffer, Buffer.GetUpperBound(0),
    
           FileName);
    
          //对Section进行解析
    
          GetStringsFromBuffer(Buffer, bufLen, Idents);
    
        }
    
    
    
        private void GetStringsFromBuffer(Byte[] Buffer, int bufLen, StringCollection Strings)
    
        {
    
          Strings.Clear();
    
          if (bufLen != 0)
    
          {
    
            int start = 0;
    
            for (int i = 0; i < bufLen; i++)
    
            {
    
              if ((Buffer[i] == 0) && ((i - start) > 0))
    
              {
    
                String s = Encoding.GetEncoding(0).GetString(Buffer, start, i - start);
    
                Strings.Add(s);
    
                start = i + 1;
    
              }
    
            }
    
          }
    
        }
    
        //从Ini文件中,读取所有的Sections的名称
    
        public void ReadSections(StringCollection SectionList)
    
        {
    
          //Note:必须得用Bytes来实现,StringBuilder只能取到第一个Section
    
          byte[] Buffer = new byte[65535];
    
          int bufLen = 0;
    
          bufLen = GetPrivateProfileString(null, null, null, Buffer,
    
           Buffer.GetUpperBound(0), FileName);
    
          GetStringsFromBuffer(Buffer, bufLen, SectionList);
    
        }
    
        //读取指定的Section的所有Value到列表中
    
        public void ReadSectionValues(string Section, NameValueCollection Values)
    
        {
    
          StringCollection KeyList = new StringCollection();
    
          ReadSection(Section, KeyList);
    
          Values.Clear();
    
          foreach (string key in KeyList)
    
          {
    
            Values.Add(key, ReadString(Section, key, ""));
    
      
    
          }
    
        }
    
        ////读取指定的Section的所有Value到列表中,
    
        //public void ReadSectionValues(string Section, NameValueCollection Values,char splitString)
    
        //{  string sectionValue;
    
        //  string[] sectionValueSplit;
    
        //  StringCollection KeyList = new StringCollection();
    
        //  ReadSection(Section, KeyList);
    
        //  Values.Clear();
    
        //  foreach (string key in KeyList)
    
        //  {
    
        //    sectionValue=ReadString(Section, key, "");
    
        //    sectionValueSplit=sectionValue.Split(splitString);
    
        //    Values.Add(key, sectionValueSplit[0].ToString(),sectionValueSplit[1].ToString());
    
     
    
        //  }
    
        //}
    
        //清除某个Section
    
        public void EraseSection(string Section)
    
        {
    
          //
    
          if (!WritePrivateProfileString(Section, null, null, FileName))
    
          {
    
    
    
            throw (new ApplicationException("无法清除Ini文件中的Section"));
    
          }
    
        }
    
        //删除某个Section下的键
    
        public void DeleteKey(string Section, string Ident)
    
        {
    
          WritePrivateProfileString(Section, Ident, null, FileName);
    
        }
    
        //Note:对于Win9X,来说需要实现UpdateFile方法将缓冲中的数据写入文件
    
        //在Win NT, 2000和XP上,都是直接写文件,没有缓冲,所以,无须实现UpdateFile
    
        //执行完对Ini文件的修改之后,应该调用本方法更新缓冲区。
    
        public void UpdateFile()
    
        {
    
          WritePrivateProfileString(null, null, null, FileName);
    
        }
    
    
    
        //检查某个Section下的某个键值是否存在
    
        public bool ValueExists(string Section, string Ident)
    
        {
    
          //
    
          StringCollection Idents = new StringCollection();
    
          ReadSection(Section, Idents);
    
          return Idents.IndexOf(Ident) > -1;
    
        }
    
    
    
        //确保资源的释放
    
        ~IniFiles()
    
        {
    
          UpdateFile();
    
        }
    
      }
    
    }
    
     
    View Code

    按行读取txt

    (函数名凭记忆写的,可能不准确,但差不多)
    
    string = File.ReadAll(filename); 获得整个文本
    
    string[] = File.ReadLines(filename); 获得整个文本,每一行作为一个string,放到数组,应该可以满足你的要求,除非文件特别大。
    
    如果你是因为文件比较大,所以要只读取其中某几行的话,那就只能建立一个file对象,一行行的读,不需要的跳过,直到读到你需要的行,因为“行”这个东西没有办法定位。
    
    如果这个需求量很大,可以考虑自己写一个索引文件,把行号对应的文件偏移量保存起来,下一次就直接seek到对应的位置开始读就可以了。
    
    霸王
    
    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Data;
    using System.Drawing;
    using System.Text;
    using System.Windows.Forms;
    
    using System.IO;
    
    namespace ReadLine_Demo
    {
        public partial class Form1 : Form
        {
            public Form1()
            {
                InitializeComponent();
            }
    
            private void button1_Click(object sender, EventArgs e)
            {
                string[] stringlines = File.ReadAllLines("d:\a.txt",Encoding.Default);
                //foreach (string s in stringlines)
                //{
                //    this.richTextBox1.Text = s;
                //    MessageBox.Show(s);
                                    
                //}
                for (int i = 3; i < 12; i++)
                {
                    if (i < stringlines.Length)
                    {
                        this.richTextBox1.Text = stringlines[i].ToString();
                        MessageBox.Show(stringlines[i].ToString());
                    }
                }
            }
        }
    }
    View Code

    用C#读写ini配置文件

    INI就是扩展名为"INI"的文件,其实他本身是个文本文件,可以用记事本打工,主要存放的是用户所做的选择或系统的各种参数.
    INI文件其实并不是普通的文本文件.它有自己的结构.由若干段落(SECTION)组成,在每个带括号的标题下面,是若干个以单个单词开头的关键字(KEYWORD)和一个等号,等号右边就是关键字的值(VALUE).例如:
    [Section1]
        KeyWord1 = Value1
        KeyWord2 = Value2
        ...
    [Section2]
        KeyWord3 = Value3
        KeyWord4 = Value4
    
    C#命名空间中没有直接读写INI的类,当然如果你把INT当成文本文件用System.IO类来读写算我没说.
    我现在介绍的是系统处理INI的方法.
    虽然C#中没有,但是在"kernel32.dll"这个文件中有Win32的API函数--WritePrivateProfileString()和GetPrivateProfileString()
    C#声明INI文件的写操作函数WritePrivateProfileString():
    [DllImport( "kernel32" )]
      private static extern long WritePrivateProfileString ( string section ,string key , string val
    , string filePath ) ;
    参数说明:section:INI文件中的段落;key:INI文件中的关键字;val:INI文件中关键字的数值;filePath:INI文件的完整的路径和名称。
    C#申明INI文件的读操作函数GetPrivateProfileString():[DllImport("kernel32")]
     private static extern int GetPrivateProfileString ( string section ,
      string key , string def , StringBuilder retVal ,
      int size , string filePath ) ;
    参数说明:section:INI文件中的段落名称;key:INI文件中的关键字;def:无法读取时候时候的缺省数值;retVal:读取数值;size:数值的大小;filePath:INI文件的完整路径和名称。
    
    下面是一个读写INI文件的类:
    public class INIClass
    {
     public string inipath;
     [DllImport("kernel32")]
     private static extern long WritePrivateProfileString(string section,string key,string val,string filePath);
     [DllImport("kernel32")]
     private static extern int GetPrivateProfileString(string section,string key,string def,StringBuilder retVal,int size,string filePath);
     /// <summary>
     /// 构造方法
     /// </summary>
     /// <param name="INIPath">文件路径</param>
     public INIClass(string INIPath)
     {
      inipath = INIPath;
     }
     /// <summary>
     /// 写入INI文件
     /// </summary>
     /// <param name="Section">项目名称(如 [TypeName] )</param>
     /// <param name="Key"></param>
     /// <param name="Value"></param>
     public void IniWriteValue(string Section,string Key,string Value)
     {
      WritePrivateProfileString(Section,Key,Value,this.inipath);
     }
     /// <summary>
     /// 读出INI文件
     /// </summary>
     /// <param name="Section">项目名称(如 [TypeName] )</param>
     /// <param name="Key"></param>
     public string IniReadValue(string Section,string Key)
     {
      StringBuilder temp = new StringBuilder(500);
      int i = GetPrivateProfileString(Section,Key,"",temp,500,this.inipath);
      return temp.ToString();
     }
     /// <summary>
     /// 验证文件是否存在
     /// </summary>
     /// <returns>布尔值</returns>
     public bool ExistINIFile()
     {
      return File.Exists(inipath);
     }
    }
     
    View Code
  • 相关阅读:
    快速傅里叶变换(FFT)
    【BZOJ】1005: [HNOI2008]明明的烦恼(prufer编码+特殊的技巧)
    【BZOJ】1030: [JSOI2007]文本生成器(递推+ac自动机)
    cf490 C. Hacking Cypher(无语)
    高精度模板2(带符号压位加减乘除开方封包)
    【BZOJ】1004: [HNOI2008]Cards(置换群+polya+burnside)
    【BZOJ】1500: [NOI2005]维修数列(splay+变态题)
    【BZOJ】1064: [Noi2008]假面舞会(判环+gcd+特殊的技巧)
    【BZOJ】1052: [HAOI2007]覆盖问题(贪心)
    【BZOJ】1028: [JSOI2007]麻将(贪心+暴力)
  • 原文地址:https://www.cnblogs.com/blogpro/p/11463259.html
Copyright © 2020-2023  润新知