天天看點

c#一些操作

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

c#一些操作
c#一些操作

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#高效分頁代碼(不用存儲過程)

c#一些操作
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>");
            }
        }
    }
}      

C#檔案讀寫

c#一些操作
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); 
            } 

        }       

C#一個顯示分頁頁碼類

c#一些操作
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;
  }
 }
}      

c#讀取txt文檔的内容并顯示在

c#一些操作
c#一些操作
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拼接字元串
\r\n換行

不太明白啊,我的txt裡,每行隻有幾個漢字,不是要拼接哦,我要分頁顯示,但是第一頁就不顯示呢,怎麼回事呢?

使用者名:caozhy  得分:0  時間:2010-12-25 09:48:43
直接ReadToEnd()就可以了。

使用者名:IHandler  得分:0  時間:2010-12-25 09:47:17
Text類型時String
用StringBuilder拼接字元串
\r\n換行
       

c#讀取大容量txt檔案怎麼才能不卡

c#一些操作
c#一些操作
多線程  
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("\r\n");
}
}
}
 
 

使用者名: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("\r\n");
 }
 }
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
這個很難吧,畢竟資料量擺在那裡,大資料量的文本讀取肯定要時間的~
       

c#開發txt文本閱讀器遇到的問題 - .NET技術  C#

c#一些操作
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
茅塞頓開      

net實作分頁顯示代碼

c#一些操作
c#一些操作
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(""); } }      

按行編讀變處理

c#一些操作
c#一些操作
邊讀邊處理,不要全部放到記憶體中
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      

按位元組數C#分塊讀取文本資料(FileStream)

c#一些操作
c#一些操作
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:\test.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方法來直接從頭讀到尾,參看下面:      

檢視TXT文檔,每頁顯示100行,一但TXT檔案超過200K後,分頁就分不了了,每頁顯示100行,一但TXT檔案超過200K後,分頁就分不了了,不知道哪裡錯了!

c#一些操作
c#一些操作
我用下列程式檢視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         

大文本如何分段讀取?-.NET技術C#

c#一些操作
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); 這樣可以實作多線程同時讀寫檔案      

分頁儲存過程

c#一些操作
c#一些操作
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      

分頁顯示思路

c#一些操作
c#一些操作
不要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);
        }      
c#一些操作
c#一些操作
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中的一小段
           }
 }
       
c#一些操作
c#一些操作
針對文本内容很大的時候,分塊來處理資料
using System.IO;
using System.Text;
 
static void ReadStreamFromFile()
        {
            string filePath = @"D:\test.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();
            }
        }      
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);      
c#一些操作
c#一些操作
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