程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> .NET網頁編程 >> C# >> C#入門知識 >> C#(winform) 操作.txt文本的例子

C#(winform) 操作.txt文本的例子

編輯:C#入門知識

 

背景:一個可輸入textbox,可以實現搜索功能

功能改進需求:把textbox改造成一個可輸入的下拉框,下拉框的內容是歷史搜索記錄(最近20次輸入搜索的內容)

www.2cto.com

代碼:

 

using System.IO;

using System.Text.RegularExpressions;

 

private ArrayList _arrSearchHistory = null; // 全局變量  form_load時讀取.txt文本中的內容 

 

// 放在form_load中 

ReadTxtFile(out _arrSearchHistory); 

if (_arrSearchHistory != null && _arrSearchHistory.Count > 0) 

    SetComboList(cboFilter, _arrSearchHistory, null, "", false, true); 

 

// 加到搜索功能中 

if (!string.IsNullOrEmpty(cboFilter.Text) && cboFilter.Text.Trim().Length>1) 

     AddItemToTxt(System.Windows.Forms.Application.StartupPath.Replace(@"bin\Debug", "") + "/Data/SearchHistory.txt", cboFilter.Text,out _arrSearchHistory); 

 

//公共函數部分 

     private void ReadTxtFile(out ArrayList arrFile,int iTopRow=20) 

     { 

         arrFile = new ArrayList(); 

         try 

         { 

             string sFileFullName = System.Windows.Forms.Application.StartupPath.Replace(@"bin\Debug", "") + @"/Data"; 

             if (!System.IO.Directory.Exists(sFileFullName)) 

             { 

                 System.IO.Directory.CreateDirectory(sFileFullName); 

             } 

 

             sFileFullName += @"/SearchHistory.txt"; 

             if (!System.IO.File.Exists(sFileFullName)) 

             { 

                 //System.IO.File.CreateText(sFileName); 

                 FileStream fs; 

                 fs = File.Create(sFileFullName); 

                 fs.Close(); 

             } 

 

             FileStream fsTxtFile = new FileStream(sFileFullName, FileMode.Open, FileAccess.Read); 

             StreamReader sr = new StreamReader(fsTxtFile, System.Text.Encoding.Default); 

             string sTemp; 

 

             sTemp = sr.ReadLine(); 

             int iTempRow=0; 

             while (!string.IsNullOrEmpty(sTemp)) 

             { 

                 iTempRow++; 

                 if (iTempRow > iTopRow) 

                 { 

                     break; 

                 } 

                 arrFile.Add(sTemp); 

                 sTemp = sr.ReadLine(); 

             } 

 

             sr.Close(); 

             sr.Dispose(); 

             fsTxtFile.Dispose(); 

         } 

         catch (Exception ex) 

         { 

             Common.DisplayMsg(this.Text, ex.Message.ToString()); 

         } 

     } 

 

     /// <summary> 

     /// 計算字符串中子串出現的次數 

     /// </summary> 

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

     /// <param name="substring">子串</param> 

     /// <returns>出現的次數</returns> 

     public  static int SubstringCount(string str, string substring) 

     { 

         if (str.Contains(substring)) 

         { 

             string strReplaced = str.Replace(substring, ""); 

             return (str.Length - strReplaced.Length) / substring.Length; 

         } 

 

         return 0; 

     } 

 

     private void AddItemToTxt(string sFileFullName, string sNewItem,out ArrayList arrFile) 

     { 

         arrFile = _arrSearchHistory; 

 

         try 

         { 

             string sTemp=""; 

             using (StreamReader sr = new StreamReader(sFileFullName)) 

             { 

                 sr.BaseStream.Flush(); 

                 sTemp = sr.ReadToEnd(); 

 

                 int iCount = SubstringCount(sTemp, "\r\n"); 

                 if (iCount > 20) 

                 { 

                     Regex reg = new Regex("\r\n"); 

                     Match mat = reg.Match(sTemp); 

                     int iCountTemp = 0; 

                     while (mat.Success) 

                     { 

                         iCountTemp++; 

                         //MessageBox.Show(mat.Index.ToString());//位置 

                         if (iCountTemp > 20) 

                         { 

                             sTemp = sTemp.Substring(0, mat.Index); 

                             break; 

                         } 

                         mat = reg.Match(sTemp, mat.Index + mat.Length); 

                     } 

                 } 

             } 

 

             //if (File.Exists(sFileFullName)) 

             //{ 

             //    File.Delete(sFileFullName); 

             //} 

 

             FileStream fsTxtWrite = new FileStream(sFileFullName, FileMode.Create, FileAccess.Write); 

             StreamWriter srWrite = new StreamWriter(fsTxtWrite, System.Text.Encoding.UTF8); 

             //StreamWriter srWrite = new StreamWriter(fsTxtWrite, System.Text.Encoding.Default); 

             if (!sTemp.Contains(sNewItem)) 

             { 

                 arrFile.Insert(0, sNewItem); 

                 srWrite.WriteLine(sNewItem); 

                 srWrite.Write(sTemp); 

             } 

             else 

             { 

                 srWrite.Write(sTemp); 

             } 

 

             srWrite.Close(); 

             srWrite.Dispose(); 

             fsTxtWrite.Dispose(); 

         } 

         catch (Exception ex) 

         { 

             Common.DisplayMsg(this.Text, ex.Message.ToString()); 

         } 

     } 

 

     //  設置下拉框   傳入參數(需要設置的下拉框控件,查詢的語句,默認第一行的內容) 

     public static void SetComboList(DevExpress.XtraEditors.ComboBoxEdit ComboList, ArrayList arrSource = null, DataTable dtSource = null, string FirstRowText = "", bool bSelectFirstItem = false, bool bEditable = false) 

     { 

         DataTable dtList = null; 

         if (dtSource != null) 

         { 

             dtList = dtSource; 

         } 

         else if (arrSource != null) 

         { 

             dtList = new DataTable(); 

             dtList.Columns.Add("name"); 

             foreach (string s in arrSource) 

             { 

                 dtList.Rows.Add(s); 

             } 

         } 

         else { return; } 

 

         int intCount = (dtList != null) ? dtList.Rows.Count : 0; 

         if (bEditable) 

         { 

             ComboList.Properties.TextEditStyle = TextEditStyles.Standard; 

         } 

         else 

         { 

             ComboList.Properties.TextEditStyle = TextEditStyles.DisableTextEditor; // 設置comboBox的文本值不能被編輯 

         } 

         ComboList.Properties.Items.Clear(); 

         if (!string.IsNullOrEmpty(FirstRowText)) ComboList.Properties.Items.Add(FirstRowText); 

 

         if (intCount > 0) 

         { 

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

             { 

                 ComboList.Properties.Items.Add(dtList.Rows[i][0].ToString()); 

             } 

         } 

         if (bSelectFirstItem) ComboList.SelectedIndex = 0; // 設置選中第1項 

     } 

 

     public static void DisplayMsg(string sCaption, string sMsg) 

     { 

         XtraMessageBox.Show(sMsg, sCaption); 

     } 

希望能幫助到有需要的人。

keenweiwei的專欄

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved