• c#一些操作


    C# FileStream 按大小分段读取文本内容

    using System.IO;
    
    
    
    namespace FileStreamRead
    {
        class Program
        {
            static void Main(string[] args)
            {
                FileStream fs;
                //获得文件所在路径
                string filePath = "C:\file1.txt";
    
                //打开文件
                try
                {
                    fs = new FileStream(filePath, FileMode.Open);
                }
                catch(Exception)
                {
                    throw;
                }
    
                //尚未读取的文件内容长度
                long left = fs.Length;
                //存储读取结果
                byte[] bytes = new byte[100];
                //每次读取长度
                int maxLength = bytes.Length;
                //读取位置
                int start = 0;
                //实际返回结果长度
                int num = 0;
                //当文件未读取长度大于0时,不断进行读取
                while (left > 0)
                {
                    fs.Position = start;
                    num = 0;
                    if (left < maxLength)
                        num = fs.Read(bytes, 0, Convert.ToInt32(left));
                    else
                        num = fs.Read(bytes, 0, maxLength);
                    if (num == 0)
                        break;
                    start += num;
                    left -= num;
                    Console.WriteLine(Encoding.UTF8.GetString(bytes));
                }
                Console.WriteLine("end of file");
                Console.ReadLine();
                fs.Close();
            }
        }
    }
    View Code

    C#高效分页代码(不用存储过程)

    using System;
    using System.Collections;
    using System.ComponentModel;
    using System.Data;
    using System.Drawing;
    using System.Web;
    using System.Web.SessionState;
    using System.Web.UI;
    using System.Web.UI.WebControls;
    using System.Web.UI.HtmlControls;
    using System.Data.SqlClient;
    using System.Configuration;
    namespace WebApplication6
    {
        /// <summary>
        /// WebForm8 的摘要说明。
        /// </summary>
        public class WebForm8 : System.Web.UI.Page
        {
            protected System.Web.UI.WebControls.LinkButton Fistpage;
            protected System.Web.UI.WebControls.LinkButton Prevpage;
            protected System.Web.UI.WebControls.LinkButton Nextpage;
            protected System.Web.UI.WebControls.LinkButton Lastpage;
            protected System.Web.UI.WebControls.DataList datalist1;
            protected System.Web.UI.WebControls.DropDownList mydroplist;
            protected System.Web.UI.WebControls.Label LPageCount;
            protected System.Web.UI.WebControls.Label LRecordCount;
            protected System.Web.UI.WebControls.Label LCurrentPage;
            protected System.Web.UI.WebControls.TextBox gotoPage;
            //定义每页显示记录
            const int PageSize = 20;
            //定义几个保存分页参数变量
            int PageCount, RecCount, CurrentPage, Pages, JumpPage;
            private void Page_Load(object sender, System.EventArgs e)
            {
                if (!IsPostBack)
                {
                    //通过Calc()函数获取总记录数
                    RecCount = Calc();
                    //计算总页数(加上OverPage()函数防止有余数造成显示数据不完整)
                    PageCount = RecCount / PageSize + OverPage();
                    //保存总页参数到ViewState(减去ModPage()函数防止SQL语句执行时溢出查询范围,可以用存储过程分页算法来理解这句)
                    ViewState["PageCounts"] = RecCount / PageSize - ModPage();
                    //保存一个为0的页面索引值到ViewState
                    ViewState["PageIndex"] = 0;
                    //保存PageCount到ViewState,跳页时判断用户输入数是否超出页码范围
                    ViewState["JumpPages"] = PageCount;
                    //显示LPageCount、LRecordCount的状态
                    LPageCount.Text = PageCount.ToString();
                    LRecordCount.Text = RecCount.ToString();
                    //判断跳页文本框失效
                    if (RecCount <= 20)
                    {
                        gotoPage.Enabled = false;
                    }
                    //调用数据绑定函数TDataBind()进行数据绑定运算
                    TDataBind();
                }
            }
            //计算余页
            public int OverPage()
            {
                int pages = 0;
                if (RecCount % PageSize != 0)
                    pages = 1;
                else
                    pages = 0;
                return pages;
            }
            //计算余页,防止SQL语句执行时溢出查询范围
            public int ModPage()
            {
                int pages = 0;
                if (RecCount % PageSize == 0 && RecCount != 0)
                    pages = 1;
                else
                    pages = 0;
                return pages;
            }
            // 计算总记录的静态函数
            // 本人在这里使用静态函数的理由是:如果引用的是静态数据或静态函数,
            // 连接器会优化生成代码,去掉动态重定位项(对海量数据表分页效果更明显)。
            // 希望大家给予意见、如有不正确的地方望指正。
            public static int Calc()
            {
                int RecordCount = 0;
                SqlCommand MyCmd = new SqlCommand("select count(*) as co from redheadedfile", MyCon());
                SqlDataReader dr = MyCmd.ExecuteReader();
                if (dr.Read())
                    RecordCount = Int32.Parse(dr["co"].ToString());
                MyCmd.Connection.Close();
                return RecordCount;
            }
            //数据库连接语句(从Web.Config中获取)
            public static SqlConnection MyCon()
            {
                SqlConnection MyConnection = new SqlConnection(ConfigurationSettings.AppSettings["DSN"]);
                MyConnection.Open();
                return MyConnection;
            }
            //对四个按钮(首页、上一页、下一页、尾页)返回的CommandName值进行操作
            private void Page_OnClick(object sender, CommandEventArgs e)
            {
                //从ViewState中读取页码值保存到CurrentPage变量中进行参数运算
                CurrentPage = (int)ViewState["PageIndex"];
                //从ViewState中读取总页参数运算
                Pages = (int)ViewState["PageCounts"];
                string cmd = e.CommandName;
                //筛选CommandName
                switch (cmd)
                {
                    case "next":
                        CurrentPage++;
                        break;
                    case "prev":
                        CurrentPage--;
                        break;
                    case "last":
                        CurrentPage = Pages;
                        break;
                    default:
                        CurrentPage = 0;
                        break;
                }
                //将运算后的CurrentPage变量再次保存至ViewState
                ViewState["PageIndex"] = CurrentPage;
                //调用数据绑定函数TDataBind()
                TDataBind();
            }
            private void TDataBind()
            {
                //从ViewState中读取页码值保存到CurrentPage变量中进行按钮失效运算
                CurrentPage = (int)ViewState["PageIndex"];
                //从ViewState中读取总页参数进行按钮失效运算
                Pages = (int)ViewState["PageCounts"];
                //判断四个按钮(首页、上一页、下一页、尾页)状态
                if (CurrentPage + 1 > 1)
                {
                    Fistpage.Enabled = true;
                    Prevpage.Enabled = true;
                }
                else
                {
                    Fistpage.Enabled = false;
                    Prevpage.Enabled = false;
                }
                if (CurrentPage == Pages)
                {
                    Nextpage.Enabled = false;
                    Lastpage.Enabled = false;
                }
                else
                {
                    Nextpage.Enabled = true;
                    Lastpage.Enabled = true;
                }
                //数据绑定到DataList控件
                DataSet ds = new DataSet();
                //核心SQL语句,进行查询运算(决定了分页的效率:))
                SqlDataAdapter MyAdapter = new SqlDataAdapter("Select Top " + PageSize + " * from redheadedfile where id not in(select top " + PageSize * CurrentPage + " id from redheadedfile order by id asc) order by id asc", MyCon());
                MyAdapter.Fill(ds, "news");
                datalist1.DataSource = ds.Tables["news"].DefaultView;
                datalist1.DataBind();
                //显示Label控件LCurrentPaget和文本框控件gotoPage状态
                LCurrentPage.Text = (CurrentPage + 1).ToString();
                gotoPage.Text = (CurrentPage + 1).ToString();
                //释放SqlDataAdapter
                MyAdapter.Dispose();
            }
            #region Web 窗体设计器生成的代码
            override protected void OnInit(EventArgs e)
            {
                //
                // CODEGEN: 该调用是 ASP.NET Web 窗体设计器所必需的。
                //
                InitializeComponent();
                base.OnInit(e);
            }
            /// <summary>
            /// 设计器支持所需的方法 - 不要使用代码编辑器修改
            /// 此方法的内容。
            /// </summary>
            private void InitializeComponent()
            {
                this.Fistpage.Command += new System.Web.UI.WebControls.CommandEventHandler(this.Page_OnClick);
                this.Prevpage.Command += new System.Web.UI.WebControls.CommandEventHandler(this.Page_OnClick);
                this.Nextpage.Command += new System.Web.UI.WebControls.CommandEventHandler(this.Page_OnClick);
                this.Lastpage.Command += new System.Web.UI.WebControls.CommandEventHandler(this.Page_OnClick);
                this.gotoPage.TextChanged += new System.EventHandler(this.gotoPage_TextChanged);
                this.Load += new System.EventHandler(this.Page_Load);
            }
            #endregion
            //跳页代码
            private void gotoPage_TextChanged(object sender, System.EventArgs e)
            {
                try
                {
                    //从ViewState中读取可用页数值保存到JumpPage变量中
                    JumpPage = (int)ViewState["JumpPages"];
                    //判断用户输入值是否超过可用页数范围值
                    if (Int32.Parse(gotoPage.Text) > JumpPage || Int32.Parse(gotoPage.Text) <= 0)
                    {
                        Response.Write("<script>alert("页码范围越界!");location.href="WebForm8.aspx"</script>");
                    }
                    else
                    {
                        //转换用户输入值保存在int型InputPage变量中
                        int InputPage = Int32.Parse(gotoPage.Text.ToString()) - 1;
                        //写入InputPage值到ViewState["PageIndex"]中
                        ViewState["PageIndex"] = InputPage;
                        //调用数据绑定函数TDataBind()再次进行数据绑定运算
                        TDataBind();
                    }
                }
                //捕获由用户输入不正确数据类型时造成的异常
                catch (Exception eXP)
                {
                    Response.Write("<script>alert("" + exp.Message + "");location.href="WebForm8.aspx"</script>");
                }
            }
        }
    }
    View Code

    C#文件读写

    1、使用FileStream读写文件 
    
    文件头: 
    
    using System; 
    using System.Collections.Generic; 
    using System.Text; 
    using System.IO; 
    
    读文件核心代码: 
    
    byte[] byData = new byte[100]; 
    char[] charData = new char[1000]; 
    
    try 
    { 
    FileStream sFile = new FileStream("文件路径",FileMode.Open); 
    sFile.Seek(55, SeekOrigin.Begin); 
    sFile.Read(byData, 0, 100); //第一个参数是被传进来的字节数组,用以接受FileStream对象中的数据,第2个参数是字节数组中开始写入数据的位置,它通常是0,表示从数组的开端文件中向数组写数据,最后一个参数规定从文件读多少字符. 
    } 
    catch (IOException e) 
    { 
    Console.WriteLine("An IO exception has been thrown!"); 
    Console.WriteLine(e.ToString()); 
    Console.ReadLine(); 
    return; 
    } 
    Decoder d = Encoding.UTF8.GetDecoder(); 
    d.GetChars(byData, 0, byData.Length, charData, 0); 
    Console.WriteLine(charData); 
    Console.ReadLine(); 
    
    写文件核心代码: 
    
    FileStream fs = new FileStream(文件路径,FileMode.Create); 
    //获得字节数组 
    byte [] data =new UTF8Encoding().GetBytes(String); 
    //开始写入 
    fs.Write(data,0,data.Length); 
    //清空缓冲区、关闭流 
    fs.Flush(); 
    fs.Close(); 
    
    2、使用StreamReader和StreamWriter 
    
    文件头: 
    
    using System; 
    using System.Collections.Generic; 
    using System.Text; 
    using System.IO; 
    
    StreamReader读取文件: 
    
    StreamReader objReader = new StreamReader(文件路径); 
          string sLine=""; 
          ArrayList LineList = new ArrayList();    
          while (sLine != null) 
          { 
            sLine = objReader.ReadLine(); 
            if (sLine != null&&!sLine.Equals("")) 
              LineList.Add(sLine); 
          } 
                objReader.Close(); 
                return LineList; 
    
    StreamWriter写文件: 
    
      FileStream fs = new FileStream(文件路径, FileMode.Create); 
    StreamWriter sw = new StreamWriter(fs); 
    //开始写入 
    sw.Write(String); 
    //清空缓冲区 
    sw.Flush(); 
    //关闭流 
    sw.Close(); 
    fs.Close(); 
    
    =================================================================================== 
    方式一:用FileStream 
    
    //实例化一个保存文件对话框 
                SaveFileDialog sf = new SaveFileDialog(); 
                //设置文件保存类型 
                sf.Filter = "txt文件|*.txt|所有文件|*.*"; 
                //如果用户没有输入扩展名,自动追加后缀 
                sf.AddExtension = true; 
                //设置标题 
                sf.Title = "写文件"; 
                //如果用户点击了保存按钮 
                if(sf.ShowDialog()==DialogResult.OK) 
                { 
                    //实例化一个文件流--->与写入文件相关联 
                    FileStream fs = new FileStream(sf.FileName,FileMode.Create); 
                    //获得字节数组 
                    byte [] data =new UTF8Encoding().GetBytes(this.textBox1.Text); 
                    //开始写入 
                    fs.Write(data,0,data.Length); 
                    //清空缓冲区、关闭流 
                    fs.Flush(); 
                    fs.Close(); 
    
                } 
    
    方式二:用StreamWriter 
    
    //实例化一个保存文件对话框 
                SaveFileDialog sf = new SaveFileDialog(); 
                //设置文件保存类型 
                sf.Filter = "txt文件|*.txt|所有文件|*.*"; 
                //如果用户没有输入扩展名,自动追加后缀 
                sf.AddExtension = true; 
                //设置标题 
                sf.Title = "写文件"; 
                //如果用户点击了保存按钮 
                if (sf.ShowDialog() == DialogResult.OK) 
                { 
                    //实例化一个文件流--->与写入文件相关联 
                    FileStream fs = new FileStream(sf.FileName, FileMode.Create); 
                    //实例化一个StreamWriter-->与fs相关联 
                    StreamWriter sw = new StreamWriter(fs); 
                    //开始写入 
                    sw.Write(this.textBox1.Text); 
                    //清空缓冲区 
                    sw.Flush(); 
                    //关闭流 
                    sw.Close(); 
                    fs.Close(); 
                } 
    
    string FileName = Guid.NewGuid().ToString() + ".txt"; //GUID生成唯一文件名 
            StringBuilder ckpw = new StringBuilder(""凭证输出", "V800", "001", "东风随州专用汽车有限公司"," + ""F89自由项16", "F90审核日期:""); 
            if (!FileIO.IsFolderExists(Server.MapPath("pzsc"))) 
                FileIO.CreaterFolder(Server.MapPath(""), "file://pzsc/"); 
            string filePath = Server.MapPath("pzsc") + "\" + FileName; 
            System.IO.StreamWriter sw = new System.IO.StreamWriter(filePath, false, Encoding.GetEncoding("GB2312"));//创建的时候需要指定编码格式,默认是UTF-8,中文显示乱码 
            sw.WriteLine(ckpw.ToString()); 
            sw.Close(); 
    
    方式三:用BinaryWriter 
    
    //实例化一个保存文件对话框 
                SaveFileDialog sf = new SaveFileDialog(); 
                //设置文件保存类型 
                sf.Filter = "txt文件|*.txt|所有文件|*.*"; 
                //如果用户没有输入扩展名,自动追加后缀 
                sf.AddExtension = true; 
                //设置标题 
                sf.Title = "写文件"; 
                //如果用户点击了保存按钮 
                if (sf.ShowDialog() == DialogResult.OK) 
                { 
                    //实例化一个文件流--->与写入文件相关联 
                    FileStream fs = new FileStream(sf.FileName, FileMode.Create); 
                    //实例化BinaryWriter 
                    BinaryWriter bw = new BinaryWriter(fs); 
                    bw.Write(this.textBox1.Text); 
                    //清空缓冲区 
                    bw.Flush(); 
                    //关闭流 
                    bw.Close(); 
                    fs.Close(); 
                } 
    
    C#缓存流示例------>用缓存流复制文件 
    
    C#文件处理操作必须先导入命名空间:using System.IO; 
    
    背景:使用VS2005、一个按钮、一个窗体、C#缓存流、把D:KuGoo爱得太多.wma复制到D:并更名为love.wma,即:D:love.wma 
    
    在按钮的Click事件中添加如下代码: 
    
    private void button1_Click(object sender, EventArgs e) 
            { 
                //创建两个文件流 一个是源文件相关,另一个是要写入的文件 
                FileStream fs = new FileStream(@"D:KuGoo爱得太多.wma",FileMode.Open); 
                FileStream fs2 = new FileStream(@"D:love.wma",FileMode.Create); 
                //创建一个字节数组,作为两者之间的媒介 
                //好比两个人拿苹果,这个字节数组就好比一个篮子,一个人作死的把苹果送到篮子里面, 
                //而我就可以作死得拿苹果,通过这个媒介我们互不干扰, 
                //不需要互相等待【她往篮子里面放了苹果我才可以去拿】,提高了效率 
                byte[] data = new byte[1024]; 
                //创建两个缓冲流,与两个文件流相关联 
                BufferedStream bs = new BufferedStream(fs); 
                BufferedStream bs2= new BufferedStream(fs2); 
                //fs作死的读,fs2作死的写,直到fs没有字节可读fs2就不写了 
               //好比,一个人作死的往篮子里面丢苹果,另一个人作死得往篮子里面拿苹果,直到篮子里面没有苹果拿了为止 
                //即-->那个人没有苹果往篮子里面放了 
                while(fs.Read(data,0,data.Length)>0) 
                { 
                    fs2.Write(data,0,data.Length); 
                    fs2.Flush(); 
                } 
                //关闭流,好比两个人累了,都要休息 呵呵o(∩_∩)o... 
                fs.Close(); 
                fs2.Close(); 
            } 
    
    
    C#内存流示例----->用内存流来读取图片 
    C#文件处理操作必须先导入命名空间:using System.IO; 
    
    背景:一个窗体、一个pictureBox、一个lable[没有选择图片,lable的text为"图片未选择"],在pictureBox1的Click事件中添加如下代码: 
    
    private void pictureBox1_Click(object sender, EventArgs e) 
            { 
                //实例化一个打开文件对话框 
                OpenFileDialog op = new OpenFileDialog(); 
                //设置文件的类型 
                op.Filter = "JPG图片|*.jpg|GIF图片|*.gif"; 
                //如果用户点击了打开按钮、选择了正确的图片路径则进行如下操作: 
                if(op.ShowDialog()==DialogResult.OK) 
                { 
                    //清空文本 
                    this.label1.Text = ""; 
                    //实例化一个文件流 
                    FileStream fs = new FileStream(op.FileName, FileMode.Open); 
                    //把文件读取到字节数组 
                    byte[] data = new byte[fs.Length]; 
                    fs.Read(data, 0, data.Length); 
                    fs.Close(); 
    
                    //实例化一个内存流--->把从文件流中读取的内容[字节数组]放到内存流中去 
                    MemoryStream ms = new MemoryStream(data); 
                    //设置图片框 pictureBox1中的图片 
                    this.pictureBox1.Image = Image.FromStream(ms); 
                } 
    
            } 
    View Code

    C#一个显示分页页码类

    在ASP.NET开发中,常用到显示分页页码程序,以下是本人写的一个类,还未完善,但已可使用,
    在显示时当前页码会自动据中。并可自定义分类链接代码
    using System;
    namespace bookshopcn.Service
    {
     /// <summary>
     /// Page 的摘要说明。
     /// </summary>
     public class Pager
     {
      public Pager(){}
      protected static int _ButtonCount = 11;
      protected static string _NextPage = "<a href={0}>下一页</a>";
      protected static string _LinkUrl = "?page={0}";
      protected static string _LastPage = "<a href={0}>上一页</a>";
      /// <summary>
      /// 下一页链接
      /// </summary>
      public static string NextPage
      {
       get{return _NextPage;}
       set{_NextPage = value;}
      }
      /// <summary>
      /// 上一页链接
      /// </summary>
      public static string LastPage
      {
       get{return _LastPage;}
       set{_LastPage = value;}
      }
      /// <summary>
      /// 设置时为格式
      /// </summary>
      public static string NextPageText
      {
       get{return _NextPage;}
       set{_NextPage = value;}
      }
      /// <summary>
      /// 显示按钮总数
      /// </summary>
      public static int BottonCount
      {
       get{return _ButtonCount;}
       set{_ButtonCount = value;}
      }
      /// <summary>
      /// 返回页面的分页信息
      /// </summary>
      /// <param name="_RecordCount">记录总数</param>
      /// <param name="_PageSize">分页长度</param>
      /// <param name="_PageIndex">当前页</param>
      /// <returns></returns>
    public static string PageInfo(int _RecordCount,int _PageSize,int _PageIndex,string link)
      {  
       string Firstpage = string.Format("<a href="+link+">[首页]</a>","1");
       string pageinfo = "共有{0}页 / 当前第{1}页 "+Firstpage;
       string pagenext = " <a href="+link+"><b>{0}</b></a> ";
       int PageCount = _RecordCount / _PageSize; // 页数合计
       PageCount = PageCount <= 0?1:PageCount;
       pageinfo = string.Format(pageinfo,PageCount.ToString(),_PageIndex.ToString());
       string LastPage = string.Format("<a href="+link+">[末页]</a>",PageCount);
       int n = _ButtonCount/2;  //左右显示个数
       int StartPage = _PageIndex - n;
       int EndPage = _PageIndex + n;
       _LastPage = string.Format(_LastPage,link);  //上一页
       _LastPage = _PageIndex-1>1?string.Format(_LastPage,(_PageIndex-1).ToString()):string.Format(_NextPage,"1");
       _NextPage = string.Format(_NextPage,link); //下一页
     _NextPage = _PageIndex+1<=PageCount?string.Format(_NextPage,_PageIndex.ToString()):string.Format(_NextPage,PageCount.ToString());
       if(EndPage > PageCount )
       {
        StartPage = (_PageIndex - n) - (EndPage-PageCount);
        EndPage = PageCount ;
       }
       if(StartPage < 1 )
       {
        EndPage = _ButtonCount;
        StartPage = 1 ;
       }
       for(int i = StartPage;i<=EndPage;i++)
       {
        if(i != _PageIndex)
         pageinfo += string.Format(pagenext,i);
        else
         pageinfo += " <b>" + i.ToString() + "</b> ";
       }
       pageinfo += LastPage;
       return pageinfo;
      }
     }
    }
    View Code

    c#读取txt文档的内容并显示在

    c#读取txt文档的内容并显示在textbox上~
      浏览:45次  时间:2010-12-25 09:35:30
     
    读取已经可以,并且用message可以,但是textBox上为什么就显示不出来呢?
    [code=C#][/code]
      int num0;
      string sc = null;
      string[] wc = new string[1000];
      string filePath = Application.StartupPath + @"word.txt";
      using (StreamReader sr = new StreamReader(filePath, System.Text.Encoding.GetEncoding("gb2312")))
      {
      while ((sc = sr.ReadLine()) != null)
      {
      wc[num] = sc;
      textBox.Text = wc[num];
        
      //MessageBox.Show(sr.ReadLine().ToString());
      num++;
      if (num > 300)
      {sr.Close(); }
      }
      }
    txt里是汉字,300行~~
    
    
    用户名:boywujch  得分:40  时间:2010-12-25 11:04:55
    C# code
    int num0; string sc = null; string[] wc = new string[1000]; string filePath = Application.StartupPath + @"word.txt"; using (StreamReader sr = new StreamReader(filePath, System.Text.Encoding.GetEncoding("gb2312"))) { while ((sc = sr.ReadLine()) != null) { wc[num] = sc; num++; if (num > 300) {sr.Close(); } } } int index = 0; textBox.Text = wc[index]; ... // 在显示下一条按钮的Click事件中index++; textBox.Text = wc[index]; if(index > 300) return;// 读取的时候只要300条,这边可以按需要处理 //index和wc提到外部就可以了
     
     
    
    用户名:caitlin_yu  得分:0  时间:2010-12-28 06:49:02
    引用 16 楼 boywujch 的回复:
    C# code
    
    int num0;
    string sc = null;
    string[] wc = new string[1000];
    string filePath = Application.StartupPath + @"word.txt";
    using (StreamReader sr = new StreamReader(filePath, System.Text.Enc……
    
    你的index在外面提醒了我,其实你的还是不显示,问题出现在静态变量上~~不过,谢谢你哈~~
    
    用户名:xiaohul305  得分:0  时间:2010-12-25 10:34:53
    我觉得是因为你用了while循环 而这个循环是在主线程中执行的 所以你要循环执行完了才会显示数据
    
    你把你这个代码放到一个新的线程中执行应该就没问题了
    
    你试试吧 我不知道对不对!?
    
    用户名:wuyq11  得分:0  时间:2010-12-25 10:24:40
    textBox.Text += wc[num];
    F11 单步查看值
    string str=File.ReadAllText(Application.StartupPath + @"word.txt")
    
    用户名:gohappy2008  得分:0  时间:2010-12-25 10:22:32
    可能是textBox控件的BackColor 和ForeColor的颜色设置成一种颜色了。
    
    其实是已经有值,但是两种颜色一样,所以显示你也看不见。
    
    我感觉应该是这样。
    
    用户名:caitlin_yu  得分:0  时间:2010-12-25 10:20:13
    引用 11 楼 dreanight 的回复:
    可以用File.ReadAllText() 一次性返回
    
    请明示?我不太懂啊~~菜鸟一个
    
    用户名:dreanight  得分:0  时间:2010-12-25 10:19:17
    可以用File.ReadAllText() 一次性返回
    
    用户名:caitlin_yu  得分:0  时间:2010-12-25 10:13:04
    引用 9 楼 boywujch 的回复:
    。。看你的代码是一次显示300行啊
    
    没有啊,我调试了,读的值赋予textBox.Text的是一行的,你说的是二楼的代码~~嘿嘿,有何高见啊?
    
    用户名:boywujch  得分:0  时间:2010-12-25 10:10:02
    。。看你的代码是一次显示300行啊
    
    用户名:caitlin_yu  得分:0  时间:2010-12-25 10:06:54
    引用 7 楼 unicorn_dsx 的回复:
    TEXTBOX多行显示,试试
    
    不是那个问题哦,我要的是每点下一步只显示一行内容,内容要把txt里的一行一行显示出来哦~~
    再说Multiline我已经设成true了
    
    用户名:unicorn_dsx  得分:0  时间:2010-12-25 10:03:17
    TEXTBOX多行显示,试试
    
    用户名:caitlin_yu  得分:0  时间:2010-12-25 10:00:12
    引用 5 楼 boywujch 的回复:
    int num0;
    string sc = null;
    string filePath = Application.StartupPath + @"word.txt";
    StringBuilder sb = new StringBuilder();
    using (StreamReader sr = new StreamReader(filePath, System.Tex……
    
     大哥,你的代码我试过了,可以调通,但是为什么把我每行的汉字都拼接起来了?而且textbox上依然没有显示哦~~
    
    用户名:boywujch  得分:0  时间:2010-12-25 09:55:25
    int num0;
      string sc = null;
      string filePath = Application.StartupPath + @"word.txt";
      StringBuilder sb = new StringBuilder();
      using (StreamReader sr = new StreamReader(filePath, System.Text.Encoding.GetEncoding("gb2312")))
      {
      while ((sc = sr.ReadLine()) != null)
      {
      sb.Append(sc);   
      num++;
      if (num > 300)
      {sr.Close(); }
      }
      textBox.Text = sb.ToString();
      }
    
    其实这样更简单
    string str = File.ReadAllText(Application.StartupPath + @"word.txt");
    textBox.Text = str;
    
    用户名:caitlin_yu  得分:0  时间:2010-12-25 09:51:05
    引用 2 楼 caozhy 的回复:
    直接ReadToEnd()就可以了。
    
    
    你好,readtoend 我用了,但是读出来的都是拼接好多字的,btw,我读文件是没有问题的,问题出现在textbox不显示上~~
    
    用户名:caitlin_yu  得分:0  时间:2010-12-25 09:49:24
    引用 1 楼 ihandler 的回复:
    Text类型时String
    用StringBuilder拼接字符串
    
    换行
    
    不太明白啊,我的txt里,每行只有几个汉字,不是要拼接哦,我要分页显示,但是第一页就不显示呢,怎么回事呢?
    
    用户名:caozhy  得分:0  时间:2010-12-25 09:48:43
    直接ReadToEnd()就可以了。
    
    用户名:IHandler  得分:0  时间:2010-12-25 09:47:17
    Text类型时String
    用StringBuilder拼接字符串
    
    换行
     
    View Code

    c#读取大容量txt文件怎么才能不卡

    多线程  
    C# code
    //例子
    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;
    using System.Threading;
    namespace MultiThread {
    public partial class Form1 : Form
    {
    public Form1() {
     InitializeComponent();
    }
    private void button1_Click(object sender, EventArgs e)
    {
    using (FolderBrowserDialog fbd = new FolderBrowserDialog())
    {
    fbd.Description = "选择要多线程读取文件的路径";
    fbd.ShowNewFolderButton = false;
    if (fbd.ShowDialog(this) == DialogResult.OK)
    {
    DirectoryInfo di = new DirectoryInfo(fbd.SelectedPath);
    foreach (FileInfo fi in di.GetFiles("*.txt"))
    {
    Thread t = new Thread(this.InvokeThread);
    t.Start(fi.FullName);
    }
    }
    }
    }
    private delegate void ReadFile(object filePath);
    private void InvokeThread(object filePath)
    {
    if (this.InvokeRequired)
    {
    this.Invoke(new ReadFile(ReadFileContent), filePath);
     }
     else {
    ReadFileContent(filePath);
     }
    }
     Private void ReadFileContent(object filePath) {
    this.textBox1.AppendText(File.ReadAllText(filePath.ToString(), Encoding.Default)); this.textBox1.AppendText("
    ");
    }
    }
    }
     
     
    
    用户名:Tsapi  得分:0  时间:2011-10-18 10:34:55
    用线程异步调用可以实现。
    C# code
    public delegate void Callback(string str); //.....class
     private void Readfile(object filepath) {
    if (textBox2.InvokeRequired) {
    Callback call = new Callback(Readfile);
    this.BeginInvoke(call,new object[]{filepath});//异步执行 
    }
    else {
    this.textBox2.AppendText(File.ReadAllText(filepath.ToString(), Encoding.Default)); this.textBox2.AppendText("
    ");
     }
     }
    private void button1_Click(object sender, EventArgs e)
    {
    using (OpenFileDialog fbd = new OpenFileDialog())
    { fbd.Filter = "(*.*)|*.txt";
    if (fbd.ShowDialog(this) == DialogResult.OK) {
    Thread t = new Thread(new ParameterizedThreadStart(Readfile));//开启线程 t.Start(fbd.FileName);
    }
     }
     }
     
     
    
    用户名:xlikena  得分:0  时间:2011-10-18 10:23:45
    C# code
    //马克
     
     
    
    用户名:xiaoyu821120  得分:0  时间:2011-10-18 10:16:17
    类似分页读取,例如很多小说阅读软件,都能快速定位,就是因为记住之前位置,在这个位置开始读取一部分数据。要一下子全部读取,当然会很慢,内存占用也大。
    
    用户名:zfvsnn  得分:0  时间:2011-10-18 10:01:20
    引用 2 楼 arnuonly 的回复:
    不难,文件分段读取。
    加一个读取文件的线程。
    每次记录上一次读取文件的游标位置。
    下一次继续。
    
    
    我对线程不熟,能给出些代码吗?
    
    用户名:zfvsnn  得分:0  时间:2011-10-18 09:58:02
    我听人说用多线程好像能,但是我对线程又不熟...所以只能跑这儿来求教....
    
    用户名:Arnuonly  得分:0  时间:2011-10-18 09:57:51
    不难,文件分段读取。
    加一个读取文件的线程。
    每次记录上一次读取文件的游标位置。
    下一次继续。
    
    用户名:fox123871  得分:0  时间:2011-10-18 09:53:44
    这个很难吧,毕竟数据量摆在那里,大数据量的文本读取肯定要时间的~
     
    View Code

    c#开发txt文本阅读器遇到的问题 - .NET技术  C#

    1.关于分页我的想法是,设法获取本窗口所能显示的行数,以及每行能显示的字数,得到所有字数,用总字数除窗口字数得到多少页,用来进行翻页。
    2.关于书签,我想首先判读本窗口第一行是总行书中的第x行,保存进书签,下次打开时,直接将本窗口第一行定位到第x行。
    遇到的问题是如果调整了窗口的大小(为了用户体验好,用户可以调整窗口大小,以及字体大小),那么本窗口显示的字数就变了,原来的行数也变了。
    3.另外我想把书签放在菜单中,就像IE浏览器的收藏夹一样。不知道这样的菜单该如何实现。
    我做的是windows程序,不是网页。
    sanler Replied at : 2012-02-15 13:45:14
    还有个问题就是我想加入朗读功能,用tts api,但是不知道如何实现当读到一段的时候让他高亮显示,就像现在的音乐播放软件一样。
    bayami Replied at : 2012-02-15 14:03:43
    TXT阅读器打开文件的时候不一定要把所有文本内容都加载,可以开一个大小固定的缓冲区,比如50K,打开文件时,加载50K的文本到缓冲区,保留指针,这50K阅读完后 ,从指针处在加载后面的50K文本,这样一直下去
    www.ahtarena.com
    sugarbelle Replied at : 2012-02-15 15:04:06
    1.参考<随读>软件.
    
    2.分页.规定多少字就分页.而不是看窗口能放多少字.
    因为人们的浏览习惯是固定的.什么资料在多少页.不管窗口怎么变.资料的位置都不会变.
    
    3.书签是直接在那个位置加上你的隐藏符号.以后不管用户怎么编辑文本.书签都能准确定位.
    
    4.用listview列表工具.把书签数组显示出来.点哪个就跳到哪个书签.
    keinshen Replied at : 2012-02-15 15:19:34
    引用 3 楼 sugarbelle 的回复:
    
    
    1.参考<随读>软件.
    
    2.分页.规定多少字就分页.而不是看窗口能放多少字.
    因为人们的浏览习惯是固定的.什么资料在多少页.不管窗口怎么变.资料的位置都不会变.
    
    3.书签是直接在那个位置加上你的隐藏符号.以后不管用户怎么编辑文本.书签都能准确定位.
    
    4.用listview列表工具.把书签数组显示出来.点哪个就跳到哪个书签.
    
    
    +1
    茅塞顿开
    View Code

    net实现分页显示代码

    using 
    using 
    using 
    using 
    using 
    using 
    using 
    using 
    using 
    using 
    using
    System; 
    System.Data; 
    System.Configuration; 
    System.Collections; 
    System.Web; 
    System.Web.Security; 
    System.Web.UI; 
    System.Web.UI.WebControls; 
    System.Web.UI.WebControls.WebParts; 
    System.Web.UI.HtmlControls; 
    System.Data.SqlClient;
        public partial class fy : System.Web.UI.Page
     { 
    public static string connstr = ConfigurationManager.ConnectionStrings["stuConnectionS tring"].ConnectionString; public SqlConnection conn; public static int pageindex = 1; public static int pagesize = 3; protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { if (Request.QueryString["pageindexa"] != null) { pageindex = Convert.ToInt16(Request.QueryString["pageindexa"].ToSt ring());
        } readrecor(); } } public void readrecor() { conn = new SqlConnection(connstr); conn.Open(); string commstr ="SELECT  FROM (SELECT ,ROW_NUMBER() OVER (ORDER BY id) AS number FROM student) AS temp WHERE temp.number BETWEEN ((@pageindex@pagesize)-(@pagesize-1)) AND (@pageindex@pagesize)"; SqlDataAdapter da = new SqlDataAdapter(commstr, conn); da.SelectCommand.CommandType = CommandType.Text; da.SelectCommand.Parameters.Add("@pageindex", SqlDbType.Int); da.SelectCommand.Parameters.Add("@pagesize", SqlDbType.Int); da.SelectCommand.Parameters[0].Value = pageindex; da.SelectCommand.Parameters[1].Value = pagesize; DataSet ds = new DataSet(); da.Fill(ds); Response.Write("
        "); Response.Write("
        "); for(int irow=0;irow<ds.Tables[0].Columns.Count-1;irow++)
        { Response.Write(""+ds.Tables[0].Columns[irow].Colum nName.ToString()+""); } Response.Write(""); for (int jrow = 0; jrow < ds.Tables[0].Rows.Count; jrow++) { Response.Write("
        "); for (int icol = 0; icol < ds.Tables[0].Columns.Count-1; icol++) { if (ds.Tables[0].Rows[jrow][icol] != null) { Response.Write("" + ds.Tables[0].Rows[jrow][icol].ToString() + ""); } else { Response.Write("&nbsp;"); } } Response.Write(""); } Response.Write(""); conn.Close(); displaypage(); } public int getpagecount()
        { conn = new SqlConnection(connstr); conn.Open(); string sql = "select count(id) from student"; SqlCommand comm = new SqlCommand(sql, conn); int zs=Convert.ToInt16(comm.ExecuteScalar()); if (zs % pagesize == 0) { zs = zs / pagesize; } else { zs = zs / pagesize + 1; } return zs; } public void displaypage() { int paa = getpagecount(); Response.Write("
        "); Response.Write("
        "); Response.Write(" 首页&nbsp;&nbsp;"); if (pageindex > 1) { Response.Write("&nbsp;&nbsp;"); } if (pageindex 
        Response.Write("&nbsp;&nbsp;"); } //for (int i = 1; i <= paa; i++) //{ // Response.Write("" + i.ToString() + "&nbsp;&nbsp;"); //} Response.Write("尾页 "); Response.Write(""); Response.Write(""); } }
    View Code

    按行编读变处理

    边读边处理,不要全部放到内存中
    new Thread((ThreadStart)delegate
      {
      StreamReader sr = new StreamReader(FileName, Encoding.GetEncoding("gb2312"));
      int line = 0;
      string line= sr.ReadLine();
      while (line!="")
      {
      line= sr.ReadLine();
      }
      sr.Close();
      }).Start();
    http://www.codeproject.com/KB/database/CsvReader.aspx
    View Code

    按字节数C#分块读取文本数据(FileStream)

    C#分块读取文本数据(FileStream)
     
    label1.text=""+(x/y)+"";
    label2.text=""+(x/z)+"";
    
    textbox1.text=内容1
    textbox2.text=内容2
    
    button1.text=后退
    button2.text=前进
    针对文本内容很大的时候,分块来处理数据
    using System.IO;
    using System.Text;
     
    
    public string filePath = @"D:	est.txt";//文件路径
    public int bufferSize = 1024; //每次读取的字节数
    public byte[] buffer = new byte[bufferSize];  //存储读取字节
    public FileStream stream = null;
    int readCount =0//需要对文件读取的次数
    int tempCount = 0;//当前已经读取的次数
    ///
    ///
    ///
    ///
    #region 
    static void ReadStreamFromFile(){
                try
    
                {
                     ReadFileStream();//stream赋值
                    long fileLength = stream.Length;//获取文本字节数长度
                    //文件流的长度
                     readCount=ReadFiletabpage();
                    //需要对文件读取的次数,页数
                  
                    do
                    {
    //分readCount次读取这个文件流,每次从上次读取的结束位置开始读取bufferSize个字节
                        stream.Read(buffer, tempCount * bufferSize, bufferSize); 
                        //这里加入接收和处理数据的逻辑-
                        string str = Encoding.Default.GetString(buffer);//判读文本编码
                        Console.WriteLine(str);
                        tempCount++;
                    }
                    while (tempCount < readCount);
                }
                catch
                {
     
                }
                finally
                {
                    if (stream != null)
                        stream.Dispose();
                }
            }
    #endregion 
    /// <summary> 
    /// WebForm1 的摘要说明。 
    /// </summary> 
     static void ReadFileStream(){
    stream = new FileStream(filePath, FileMode.Open);
     }
    
    ///
    ///
    ///
    ///
    public long GetFileLength()
    {
    long fileLength = stream.Length;//获取文本字节数长度
    return fileLength;
    }
    ///
    ///
    ///
    ///
    static ini ReadFiletabpage(){
    return  (int)Math.Ceiling((double)(fileLength / bufferSize)); 
    //需要对文件读取的次数,页数
     }
    其中:
    stream.Read(buffer, tempCount * bufferSize, bufferSize)
     
    其实就是使用Read来读取分块段,使用一个计数器tempCount来标识下读取到哪段了,再从这个位置继续往下读取自定义长度bufferSize的数据
     
     
    如果文本数据不是很大,还可以使用StreamReader方法来直接从头读到尾,参看下面:
    View Code

    查看TXT文档,每页显示100行,一但TXT文件超过200K后,分页就分不了了,每页显示100行,一但TXT文件超过200K后,分页就分不了了,不知道哪里错了!

    我用下列程序查看txt文档,并在每页显示100行,但是一但txt文件超过200k后,分页就分不了了,不知道哪里错了!filename="3dfdsfsa.txt"   
        
                                filename=server.mappath   (filename)   
                              set   accessfile   =   createobject("scripting.filesystemobject")   
        if   accessfile.fileexists(filename)   then     
                                set   file   =   accessfile.opentextfile(filename)   
                dim   html(100)   
      i=1   
      j=1   
      html(j)=""   
      do   while   not   file.atendofstream   
        p=file.readline   
        html(j)=html(j)&"  "&p&"<br>"   
        i=i+1   
        if   (i   mod   100)=0   then     
          j=j+1   
          i=0   
          html(j)=""   
        end   if   
      loop   
    View Code

    大文本如何分段读取?-.NET技术C#

    做了个读文本的小程序,一行一行的读,用dataGridView显示出来。发现大开大一点的文件会比较慢(100M,大约20秒的样子),虽然很少会去打开这么大的,但是想问下向word那样有个整体的进度,滚动条拉到哪就读到哪里是怎么做到的?
    大家有点想法都说说哈~
    ------回答---------
     
    ------其他回答(10分)---------
    
    边读边处理,不要全部放到内存中
    new Thread((ThreadStart)delegate
      {
      StreamReader sr = new StreamReader(FileName, Encoding.GetEncoding("gb2312"));
      int line = 0;
      string line= sr.ReadLine();
      while (line!="")
      {
      line= sr.ReadLine();
      }
      sr.Close();
      }).Start();
    http://www.codeproject.com/KB/database/CsvReader.aspx------其他回答(10分)---------
    
    既然你本身就是一行行读的,就应该就不是读的问题了,而是你将100M的文件都显示出来的原因吧。100M的内容用20秒显示出来算快的了。
    word及urltraedit之类的软件能快速打开大文件,肯定是不会一次性全部读取的,我没研究过,但觉得应该只读取了当前需要显示出来的一部分及后续可能显示的一部分,其它的部分类容只是在后台做索引,当滚动条滚动到那个地方的时候再根据索引快速定位读取显示那一部分。------其他回答(5分)---------
     
    C# code
    FileStream fs = new FileStream("c:\abc.txt", FileMode.Open, FileAccess.Read); fs.Position = 40000000; // 读取的内容的开始位置 byte[] buffer = new byte[100]; // 缓存数据的buffer fs.Read(buffer, 0, 90); // 读取数据 fs.Close();
     
     
    
    想读哪儿读哪儿,想读多少就读多少。------其他回答(5分)---------
     
    C# code
    用FileStream FileStream fw = new FileStream(newFileName, FileMode.Append, FileAccess.Read, FileShare.Read); fw.Seek(1024, SeekOrigin.Begin); fw.Read(myByte, 0, myByte.Length); 不仅可以随机读写,还可以用异步方式 fw.BeginRead(myData.Buffer, 0, assignSize, new AsyncCallback(AsyncRead), myData); 这样可以实现多线程同时读写文件
    View Code

    分页储存过程

    CREATE PROCEDURE [dbo].[UP_GetRecordByPage]
        @tblName      varchar(255),       -- 表名
        @fldName      varchar(255),       -- 主键字段名
        @PageSize     int = 10,           -- 页尺寸
        @PageIndex    int = 1,            -- 页码
        @IsReCount    bit = 0,            -- 返回记录总数, 非 0 值则返回
        @OrderType    bit = 1,            -- 设置排序类型, 非 0 值则降序
        @strWhere     varchar(1000) = '' -- 查询条件 (注意: 不要加 where)
    AS
    
    declare @strSQL   varchar(6000)       -- 主语句
    declare @strTmp   varchar(1000)        -- 临时变量(查询条件过长时可能会出错,可修改100为1000)
    declare @strOrder varchar(400)        -- 排序类型
    
    if @OrderType != 0
    begin
        set @strTmp = '<(select min'
        set @strOrder = ' order by [' + @fldName +'] desc'
    end
    else
    begin
        set @strTmp = '>(select max'
        set @strOrder = ' order by [' + @fldName +'] asc'
    end
    
    set @strSQL = 'select top ' + str(@PageSize) + ' * from ['
        + @tblName + '] where [' + @fldName + ']' + @strTmp + '(['
        + @fldName + ']) from (select top ' + str((@PageIndex-1)*@PageSize) + ' ['
        + @fldName + '] from [' + @tblName + ']' + @strOrder + ') as tblTmp)'
        + @strOrder
    
    if @strWhere != ''
        set @strSQL = 'select top ' + str(@PageSize) + ' * from ['
            + @tblName + '] where [' + @fldName + ']' + @strTmp + '(['
            + @fldName + ']) from (select top ' + str((@PageIndex-1)*@PageSize) + ' ['
            + @fldName + '] from [' + @tblName + '] where ' + @strWhere + ' '
            + @strOrder + ') as tblTmp) and ' + @strWhere + ' ' + @strOrder
    
    if @PageIndex = 1
    begin
        set @strTmp =''
        if @strWhere != ''
            set @strTmp = ' where ' + @strWhere
    
        set @strSQL = 'select top ' + str(@PageSize) + ' * from ['
            + @tblName + ']' + @strTmp + ' ' + @strOrder
    end
    
    if @IsReCount != 0
        set @strSQL = 'select count( *  ) as Total from [' + @tblName + ']'+' where ' + @strWhere
    
    exec (@strSQL)
    GO
    View Code

    分页显示思路

    不要readtoend一次全读出来
    循环中,每次读一定数量的字符就行 
    
    string[] lines=File.ReadAllLines("");
    lines.Skip(1).Take(1);
    
    
    
    
    页数 由 总行数 和每页的行数 来控制
    总行数和每页行数 由字符数、显示区长度、宽度、字体大小、边距 等控制
    
    
    
    
    
    StreamRead sr = new StreamRead("目录");
    
    int cnt = 0;
    int PageMax = 10;
    
    //此处封装成递归或者for循环以达到添加所有txt内容
    for(int i = 0;i < PageMax ;i++)
    {
        if(cnt<PageMax)
           break;
        sr.ReadLine();
        //你的操作,实例化第二页
        cnt++;
    }
    
    
    
    
    long lCurrPos = 0;
            public Form1()
            {
                InitializeComponent();
            }
    
            private void button1_Click(object sender, EventArgs e)
            {
                string Str = "abc.txt";
                FileStream FS = new FileStream(Str, FileMode.Open);
                FS.Position = lCurrPos;
                byte[] bdata = new byte[1024];
                int iResult = FS.Read(bdata, 0, bdata.Length - 1);
                //如果是汉字文档,此处易出现乱码
                if (bdata[iResult - 1] > 127)
                {
                    iResult = iResult + FS.Read(bdata, bdata.Length - 1, 1);
                }
                lCurrPos = FS.Position;
                FS.Close();
                FS = null;
                Str = Encoding.Default.GetString(bdata, 0, iResult);
                Array.Clear(bdata, 0, bdata.Length);
                textBox1.Text = Str;
            }
    
    
    
    
    public static string ReadFiles(string path)
            {
                switch (PathExtraction.GetType(path.ToLower()))
                {
                    case ".txt": return ReadFile.TxtFile(path);
                    default: return "不支持的文件格式"; 
                }
            }
            public static string TxtFile(string path)
            {
                System.IO.FileStream fs = new System.IO.FileStream(path, System.IO.FileMode.Open, System.IO.FileAccess.Read);
                byte[] bytes = new byte[fs.Length];
                fs.Read(bytes, 0, (int)fs.Length);
                fs.Dispose();
                fs.Close();
                return Encoding.Default.GetString(bytes);
            }
    View Code

    关于读取txt文件的分段问题

    txt文件格式如下:
    
    [属性1]
    参数=2210.3,12.65,115,25,420.66,445.69,0.569
    [属性2]
    9,0.018,2003-10,@
    J01,1,3751508.5,39438683.65
    J02,1,3751508.5,39438690.15
    5,0.0247,2003-12,@
    J01,1,3755389.7,39437380.2
    
    
    怎样把属性1和属性2分离出来?属性一算是一段,属性2算是另一段,属性2中可能有多个以‘@’结尾的部分又需要分成多个小段。
    我主要是想将txt分成3部分,一个是属性1和属性2之间的那一段,第二部分是以‘@’结尾的那一行到下一个以'@'结尾的那一行之前的那一段,就是示例 中的第4、5、6三行,第三部分就是之后的7、8两行,也就是和第二部分差不多的,要求要是有多个‘@’结尾的部分的话要求能分成多段。
    
    不知道我说明白没有,不明白的一起讨论一下!
    
    成果:
            /// <summary>
           /// Gets the ZD array.
            /// </summary>
           /// <param name="fileName">Name of the file.</param>
           /// <returns></returns>
           private ArrayList GetZDArray(string fileName)
            {
               //读取文件内容
                StreamReader sr = new StreamReader(fileName, System.Text.Encoding.Default);
                string tempStr = ""; //sr.ReadLine();
                ArrayList ArrList = new ArrayList();
                ArrayList csArrList = new ArrayList();
               ArrayList dkArrList = new ArrayList();
                ArrayList zbArrList = new ArrayList();
    
                //初步整理文件内容并读出至ArrList中
                while ((tempStr = sr.ReadLine()) != null)
               {
                   tempStr = tempStr.Trim();
                   if (tempStr.Length < 1)
                        continue;
                   if (tempStr.IndexOf("[属性1]") == 0 ||tempStr.IndexOf("[属性2]") == 0)
                   {
                       continue;
                    }
                   else if (tempStr.Split('=').Length > 1)
                    {
                       csArrList.Add(tempStr);
                    }
                  else
                    {
                       dkArrList.Add(tempStr);
                    }
               }
               sr.Close();
               ArrList.Add(csArrList);
               ArrList.Add(dkArrList);
                return ArrList;
           }
    
     /// <summary>
            /// Gets the ZB STR from array.
            /// </summary>
            /// <param name="ArrList">The arr list.</param>
            /// <returns></returns>
            private string GetZBStrFromArray(ArrayList ArrList)
            {
                string dkstr = "";
                string tem = "";
                int spl = 0;
               for (int i = 0; i < ArrList.Count; i++)
                {
                   tem = (string)ArrList[i];
                    if (tem.Trim().Length < 1)
                        continue;
                    if (tem.Substring(tem.Length - 1, 1) == "@")
                    {
                        //continue;
                      spl++;
                       dkstr = dkstr + "#" + tem;
                  }
                   else
                   {
                        dkstr = dkstr + tem + "$";
                   }
     
                 }
               return dkstr;
            }
     private bool InsertDKAndZB(string dkzbStr)
    {
              string[] dkandzb = dkzbStr.Split('#');
                for (int i = 0; i < dkandzb.Length; i++)
                {
                    string val1 = "";
                  if (dkandzb[i].Trim().Length < 1)
                        continue;
                    string[] dkStr = dkandzb[i].Split('@');
                   //dkStr  就是属性2中的一小段
               }
     }
     
    View Code

    针对文本内容很大的时候,分块来处理数据

    针对文本内容很大的时候,分块来处理数据
    using System.IO;
    using System.Text;
     
    static void ReadStreamFromFile()
            {
                string filePath = @"D:	est.txt";
                int bufferSize = 1024; //每次读取的字节数
                byte[] buffer = new byte[bufferSize];
                FileStream stream = null;
                try
                {
                    stream = new FileStream(filePath, FileMode.Open);
                    long fileLength = stream.Length;//文件流的长度
                    int readCount = (int)Math.Ceiling((double)(fileLength / bufferSize)); //需要对文件读取的次数
                    int tempCount = 0;//当前已经读取的次数
                    do
                    {
                        stream.Read(buffer, tempCount * bufferSize, bufferSize); //分readCount次读取这个文件流,每次从上次读取的结束位置开始读取bufferSize个字节
                        //这里加入接收和处理数据的逻辑-
                        string str = Encoding.Default.GetString(buffer);
                        Console.WriteLine(str);
                        tempCount++;
                    }
                    while (tempCount < readCount);
                }
                catch
                {
     
                }
                finally
                {
                    if (stream != null)
                        stream.Dispose();
                }
            }
    View Code
    Graphics gh(hdc);    
    Image img(L"c:\test.jpg");
    Point destPoints[] = {
    Point(100, 120),
    Point(300, 120),
    Point(120, 160)
    };
    Point destPoints2[] = {
    Point(120, 180),
    Point(320, 180),
    Point(100, 220)
    };
    
    
    for(int i=0; i<300; i++)
    gh.DrawImage(&img, 0, 0);
    
    for(i=0; i<300; i++)
    gh.DrawImage(&img, destPoints, 3);
    
    gh.DrawImage(&img, destPoints2, 3);
    using System.Runtime.InteropServices;
    using System.Diagnostics;
     #region  优化
                Stopwatch timer = new Stopwatch();
    
                // initialize your code here 
    
                GC.Collect(2);
                GC.WaitForPendingFinalizers();
                GC.Collect(2);
                GC.WaitForPendingFinalizers();
    
                timer.Start();
    
                //Do your test here 
    
                timer.Stop();
    
                Console.WriteLine(timer.ElapsedMilliseconds.ToString());
     #endregion
    View Code
  • 相关阅读:
    使用Beautiful Soup扒取指定标题
    平时笔记
    2017年暑期大数据培训小记
    ZoomIt的使用方法
    ASP.NET使用富文本控件KindEditor(一步到位,亲测有效)
    ASP.NET使用Ajax返回Json对象
    Python简易爬虫
    Class.forName()用法详解
    【4-1】js函数、事件、补充知识
    【3-30】document获取、事件、标记样式
  • 原文地址:https://www.cnblogs.com/blogpro/p/11457080.html
Copyright © 2020-2023  润新知