C # dealing with a text file

Author:Anonymous    Updated:2008-3-4 12:12:53
Text files is a common file format, how to handle text files have become a focus of programming. In this paper to explore how to use C # is to handle text files. Its content is focused on how to read a text file, how to change the text of the contents of the documents, as well as how to use the C # to realize after reading the text of the document Print Preview and Print.

1. In this paper the design and operation procedures for the software environment:

(1). Version of Microsoft Windows 2000 server

(2) .. Net FrameWork SDK Beta 2

2. C # dealing with a text file of some important links:

(1) how to read a text file:

In this paper, the procedure is to read the text files, with a richTextBox components displayed. To read a text file, you must use the "StreamReader" class that is the name space, "System.IO" in the definition. Through "StreamReader" "ReadLine ()" method, we can read the data stream will open the data. Below is the function of code reading "C: \ file.txt" and displayed richTextBox1 components:

     FileStream fs = new FileStream ( "C: \ \ file.txt", FileMode.Open, FileAccess.Read);
         StreamReader m_streamReader = new StreamReader (fs);
     / / Use the StreamReader class to read documents
     M_streamReader.BaseStream.Seek (0, SeekOrigin.Begin);
         / / From the data stream read each row, until the last line of the paper, and the content displayed richTextBox1
         This.richTextBox1.Text = "";
         M_streamReader.ReadLine string strLine = ();
         While (strLine! = Null)
         (
             This.richTextBox1.Text strLine + + = "\ n";
             StrLine = m_streamReader.ReadLine ();
         )
         / / Close this StreamReader object
         M_streamReader.Close ();


(2) how to change the content of data in a text file:

In this paper, in the process, change the text content of the data by changing the function of the content of richTextBox1 to achieve, and when richTextBox1 the contents of this change, rather than pressing the "Save", they richTextBox1 the contents of the designated storage in a text file. To change the text content of the document, to be used to "StreamWriter", and "StreamReader", were from "System.IO" to the definition of the name space. Through "StreamWriter" "Write ()" method, we can easily change the text content of the document. Below is the function of code: If the "C" was there, "file.txt", and put the content into the richTextBox1 "file.txt", where they do not exist, the creation of this document, and then write text data.

     / / Create a document flow, or write to create a StreamWriter
     FileStream fs = new FileStream ( "C \ \ file.txt" FileMode.OpenOrCreate, FileAccess.Write);
         StreamWriter m_streamWriter = new StreamWriter (fs);
         M_streamWriter.Flush ();
         / / Use StreamWriter content from the paper writes
         M_streamWriter.BaseStream.Seek (0, SeekOrigin.Begin);
         / / The contents of the richTextBox1 writes the document
         M_streamWriter.Write (richTextBox1.Text);
         / / Close this document
         M_streamWriter.Flush ();
         M_streamWriter.Close ();


This two from the above code can read data into the data than it should be easier.

(3) How to achieve Print Preview:

Print preview is through the Print Preview dialog to achieve, and the realization of the text read print preview, the most important thing is to inform the Print Preview dialog to be a preview of the contents of the documents. Below is the code that the content in the richTextBox1 through the Print Preview dialog box is displayed:

RichTextBox1.Text string strText =;
     StringReader myReader = new StringReader (strText);
     PrintPreviewDialog printPreviewDialog1 = new PrintPreviewDialog ();
     PrintPreviewDialog1.Document = ThePrintDocument;
     PrintPreviewDialog1.FormBorderStyle = FormBorderStyle.Fixed3D;
     PrintPreviewDialog1.ShowDialog ();


(4) How to print documents:

In the name space, "System.Drawing.Printing" in the definition of a category "PrintDocument" by calling such "Print" method can be triggered in the name of this package in the space of another incident, "PrintPage." In this incident set a document to print, so as to achieve teams text file printing operation. Below code is called "PrintDocument", "Print", and called the incident "PrintPage" richTextBox1 to print the contents:

ThePrintDocument.Print (); / / which ThePrintDocument "PrintDocument" of an object

The following code is set richTextBox1 Print Print content is the content:

             Float linesPerPage = 0;
                 Float yPosition = 0;
                 Int count = 0;
                 Float leftMargin = ev.MarginBounds.Left;
                 Float topMargin = ev.MarginBounds.Top;
                 = Null string line;
                 Font printFont = richTextBox1.Font;
                 SolidBrush myBrush = new SolidBrush (Color.Black);
                 / / Calculate how much each page to print
             LinesPerPage = ev.MarginBounds.Height / printFont.GetHeight (ev.Graphics);
                 / / Repeated use StringReader object, print out of all the content richTextBox1
                 While (count <linesPerPage & & ((line = myReader.ReadLine ())! = Null))
             (
/ / Print calculated to the next line is based on the location of pages
     YPosition topMargin + = (count * printFont.GetHeight (ev.Graphics));
     / / Print richTextBox1 content in the next line
     Ev.Graphics.DrawString (line, printFont, myBrush, leftMargin, yPosition, new StringFormat ());
     Count + +;
                 )
                 / / If the judge also Next, will continue to Print
                 If (line! = Null)
     Ev.HasMorePages = true;
                 Else
     Ev.HasMorePages = false;
                 MyBrush.Dispose ();


Notes: As in the above code saved by these types of space for the name, in order to successfully build and run the above code, it is necessary to head to import procedures used by the name space.

3. Using C # version of the integrity of the document dealing with the source code (control.cs):

Master these critical steps above, it can be convenient to handle with C # a complete text of the source code, as follows:

     Using System;
         Using System.Drawing;
         Using System.Collections;
         Using System.ComponentModel;
         Using System.Windows.Forms;
         Using System.Data;
         Using System.IO;
         Using System.Drawing.Printing;
     Public class Form1: Form
     (
     Private RichTextBox richTextBox1;
     Private Button button1;
     Private Button button2;
     Private Button button3;
     Private Button button4;
     Private Button button5;
     Private OpenFileDialog openFileDialog1;
     Private SaveFileDialog saveFileDialog1;
     Private PrintDialog printDialog1;
     Private PrintDocument ThePrintDocument;
     Private PrintPreviewDialog printPreviewDialog1;
                         Private StringReader myReader;
     Private System.ComponentModel.Container components = null;
    
     Public Form1 ()
     (
     / / Initialization for various components in the form
     InitializeComponent ();
     )
     / / Clearance procedures in the use of more resources
     Protected override void Dispose (bool disposing)
     (
     If (disposing)
     (
     If (components! = Null)
(
Components.Dispose ();
     )
     )
     Base.Dispose (disposing);
     )
     Private void InitializeComponent ()
     (
     RichTextBox1 = new RichTextBox ();
     Button1 = new Button ();
     Button2 = new Button ();
     Button3 = new Button ();
     Button4 = new Button ();
     Button5 = new Button ();
                     SaveFileDialog1 = new SaveFileDialog ();
                     OpenFileDialog1 = new OpenFileDialog ();
     PrintPreviewDialog1 = new PrintPreviewDialog ();
     PrintDialog1 = new PrintDialog ();
     ThePrintDocument = new PrintDocument ();
                                                     ThePrintDocument.PrintPage + = new PrintPageEventHandler (ThePrintDocument_PrintPage);
     SuspendLayout ();
     RichTextBox1.Anchor = AnchorStyles.None;
     RichTextBox1.Name = "richTextBox1";
     RichTextBox1.Size new Size = (448, 280);
     RichTextBox1.TabIndex = 0;
     RichTextBox1.Text = "";
     Button1.Anchor = AnchorStyles.None;
     Button1.Location = new Point (41, 289);
     Button1.Name = "button1";
     Button1.Size = new Size (48, 30);
     Button1.TabIndex = 1;
     Button1.Text = "open";
     Button1.Click + = new System.EventHandler (button1_Click);
     Button2.Anchor = AnchorStyles.None;
     Button2.Location = new Point (274, 288);
     Button2.Name = "button2";
     Button2.Size = new Size (48, 30);
     Button2.TabIndex = 4;
     Button2.Text = "preview";
     Button2.Click + = new System.EventHandler (button2_Click);
     Button3.Anchor = AnchorStyles.None;
     Button3.Location = new Point (108, 288);
     Button3.Name = "button3";
     Button3.Size = new Size (48, 30);
     Button3.TabIndex = 2;
     Button3.Text = "preserve";
     Button3.Click + = new System.EventHandler (button3_Click);
     Button4.Anchor = AnchorStyles.None;
     Button4.Location = new Point (174, 288);
     Button4.Name = "button4";
     Button4.Size = new Size (80, 30);
     Button4.TabIndex = 3;
     Button4.Text = "Printer Setup";
     Button4.Click + = new System.EventHandler (button4_Click);
     Button5.Anchor = AnchorStyles.None;
     Button5.Location = new Point (345, 288);
     Button5.Name = "button5";
     Button5.Size = new Size (48, 30);
     Button5.TabIndex = 5;
     Button5.Text = "Print";
     Button5.Click + = new System.EventHandler (button5_Click);
                   SaveFileDialog1.DefaultExt = "*. txt";
             SaveFileDialog1.FileName = "file.txt";
     SaveFileDialog1.InitialDirectory = "c: \ \";
     SaveFileDialog1.Title = "Save As";
     OpenFileDialog1.DefaultExt = "*. txt";
     OpenFileDialog1.FileName = "file.txt";
     OpenFileDialog1.InitialDirectory = "c: \ \";
     OpenFileDialog1.Title = "open text file!";
     AutoScaleBaseSize new Size = (6, 14);
     ClientSize new Size = (448, 325);
     This.Controls.Add (button1);
     This.Controls.Add (button2);
     This.Controls.Add (button3);
     This.Controls.Add (button4);
     This.Controls.Add (button5);
     This.Controls.Add (richTextBox1);
    
     This.MaximizeBox = false;
     This.Name = "Form1";
     This.Text = "C # to operate a text file";
     This.ResumeLayout (false);
     )
     Static void Main ()
(
Application.Run (new Form1 ());
     )
    
     Private void button1_Click (object sender, System.EventArgs e)
     (
                 Try
                 (
     If (openFileDialog1.ShowDialog () == DialogResult.OK)
     (
         FileStream fs = new FileStream (openFileDialog1.FileName, FileMode.Open, FileAccess.Read);
         StreamReader m_streamReader = new StreamReader (fs);
     / / Use the StreamReader class to read documents
     M_streamReader.BaseStream.Seek (0, SeekOrigin.Begin);
         / / From the data stream read each row, until the last line of the paper, and the content displayed richTextBox1
         This.richTextBox1.Text = "";
         M_streamReader.ReadLine string strLine = ();
         While (strLine! = Null)
         (
             This.richTextBox1.Text strLine + + = "\ n";
             StrLine = m_streamReader.ReadLine ();
         )
         / / Close this StreamReader object
         M_streamReader.Close ();
     )
             )
             Catch (Exception em)
                 (
     Console.WriteLine (em.Message.ToString ());
                 )
    
     )
    
     Private void button3_Click (object sender, System.EventArgs e)
     (
                 Try
                 (
     / / Save the file name
     If (saveFileDialog1.ShowDialog () == DialogResult.OK)
     (
     / / Create a document flow, or write to create a StreamWriter
     FileStream fs = new FileStream (@ saveFileDialog1.FileName, FileMode.OpenOrCreate, FileAccess.Write);
         StreamWriter m_streamWriter = new StreamWriter (fs);
         M_streamWriter.Flush ();
    
         / / Use StreamWriter content from the paper writes
         M_streamWriter.BaseStream.Seek (0, SeekOrigin.Begin);
         / / The contents of the richTextBox1 writes the document
         M_streamWriter.Write (richTextBox1.Text);
         / / Close this document
         M_streamWriter.Flush ();
         M_streamWriter.Close ();
     )
                 )
                 Catch (Exception em)
                 (
     Console.WriteLine (em.Message.ToString ());
                 )
     )
    
     Private void button4_Click (object sender, System.EventArgs e)
     (
                 PrintDialog1.Document = ThePrintDocument;
                 PrintDialog1.ShowDialog ();
     )
     / / Print Preview document
     Private void button2_Click (object sender, System.EventArgs e)
     (
                 Try
                 (
     RichTextBox1.Text string strText =;
     MyReader = new StringReader (strText);
     PrintPreviewDialog printPreviewDialog1 = new PrintPreviewDialog ();
     PrintPreviewDialog1.Document = ThePrintDocument;
     PrintPreviewDialog1.FormBorderStyle = FormBorderStyle.Fixed3D;
     PrintPreviewDialog1.ShowDialog ();
                 )
                 Catch (Exception exp)
                 (
     Console.WriteLine (exp.Message.ToString ());
                 )
     )
     / / Print the contents of richTextBox1
     Private void button5_Click (object sender, System.EventArgs e)
     (
                 PrintDialog1.Document = ThePrintDocument;
                 RichTextBox1.Text string strText =;
                 MyReader = new StringReader (strText);
                 If (printDialog1.ShowDialog () == DialogResult.OK)
                 (
     ThePrintDocument.Print ();
                 )
     )
                 Protected void ThePrintDocument_PrintPage (object sender, PrintPageEventArgs ev)
                             (
                 Float linesPerPage = 0;
                 Float yPosition = 0;
                 Int count = 0;
                 Float leftMargin = ev.MarginBounds.Left;
                 Float topMargin = ev.MarginBounds.Top;
                 = Null string line;
                 Font printFont = richTextBox1.Font;
                 SolidBrush myBrush = new SolidBrush (Color.Black);
                 / / Calculate how much each page to print
             LinesPerPage = ev.MarginBounds.Height / printFont.GetHeight (ev.Graphics);
                 / / Repeated use StringReader object, print out of all the content richTextBox1
                 While (count <linesPerPage & & ((line = myReader.ReadLine ())! = Null))
             (
/ / Print calculated to the next line is based on the location of pages
     YPosition topMargin + = (count * printFont.GetHeight (ev.Graphics));
     / / Print richTextBox1 content in the next line
     Ev.Graphics.DrawString (line, printFont, myBrush, leftMargin, yPosition, new StringFormat ());
     Count + +;
                 )
                 / / If the judge also Next, will continue to Print
                 If (line! = Null)
     Ev.HasMorePages = true;
                 Else
     Ev.HasMorePages = false;
                 MyBrush.Dispose ();
       )
           )


4. Summary:

Although only on paper using C # handle text files, but in fact the C # with other documents also have a lot of value, it is because in the name space, "System.IO" in the definition of other documents for the processing of the class structure and text documents for the processing of the structure of many of the same. Hope that this paper you use C # programming documents for help
Previous:Prepared to expand the use of C # stored procedure
Next:C # Access Interface
User Reviews
Recommended article
AD