C # (winform) Example of operating the .txt text

Source: Internet
Author: User

 

Background: A textbox can be input to implement the search function.

Function Improvement requirement: the textbox is transformed into an input drop-down box. The content of the drop-down box is a historical search record (the content of the last 20 input searches)

Www.2cto.com

Code:

 

Using System. IO;

Using System. Text. RegularExpressions;

 

Private ArrayList _ arrSearchHistory = null; // The global variable form_loadreads the content in the. TXT text.

 

// Put it in form_load

ReadTxtFile (out _ arrSearchHistory );

If (_ arrSearchHistory! = Null & _ arrSearchHistory. Count> 0)

{

SetComboList (cboFilter, _ arrSearchHistory, null, "", false, true );

}

 

// Added to the search function

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 );

}

 

// Public Functions

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>

/// Calculate the number of times a substring appears.

/// </Summary>

/// <Param name = "str"> string </param>

/// <Param name = "substring"> substring </param>

/// <Returns> Number of occurrences </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 (); // location

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 ());

}

}

 

// Set parameters in the drop-down box (the drop-down box control to be set, the query statement, the content of the first line by default)

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; // You Cannot edit the comboBox text value.

}

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; // you can specify 1st items.

}

 

Public static void DisplayMsg (string sCaption, string sMsg)

{

XtraMessageBox. Show (sMsg, sCaption );

}

Hope to help people in need.

Keenweiwei's column

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.