C # handling text files

xiaoxiao2021-03-06  85

Text file is a common file format, so how to deal with text files will become a focus of programming. This article discusses how to handle text files with C #. Its content is how to read text file content, how to change text files, and how to use C # to implement print previews and prints for read text files.

One. This article is designed and running software environment:

(1). Microsoft Window 2000 Server Edition (2) .. Net Framework SDK Beta 2

two. C # to handle some important part of the text file:

(1). How to read the text file: In the program introduced in this article, the text file read is displayed in a RichTextBox component. To read a text file, you must use the "StreamReader" class, which is defined by the namespace "System.IO". With the "READLINE ()" method of the "StreamReader" class, you can read the data that opens the data traffic for preceding. The following code implemented is to read "c: /file.txt" and display it in the RichtextBox1 component:

FileStream fs = new FileStream ( "C: //file.txt", FileMode.Open, FileAccess.Read); StreamReader m_streamReader = new StreamReader (fs); // Use StreamReader class to read the file m_streamReader.BaseStream.Seek (0 , Seekorigin.begin; // read each line from the data stream until the last line of the file, and display content this.richtextbox1.text = "in RichTextBox1, string strline = m_streamreader.readline (); while Strline! = null) {this.richtextbox1.text = strline "/ n"; strline = m_streamReader.readLine ();} // Close this StreamReader object m_streamReader.close ();

Its implementation is as follows:

Figure 01: Read the text file and display it

(2). How to change the data content in the text file: In the program introduced in this article, the function of changing the text file data is achieved by changing the content in RichTextBox1. When the content of the RichtextBox1 changes, "Save as Save" ", Store the contents of the content in RichTextBox1 to the specified text file. To change text file content, use the "streamwriter" class, this class and "streamreader" are defined by the "System.IO" name space. The text file content can be easily changed by the "Write ()" method of the "StreamWriter" class. The following code is: If there is "File.txt" if the "C" disk exists, write the contents in RichTextBox1 to "File.txt", if there is no existence, create this file, and then write text data. // Create a file stream for write or create a StreamWriter FileStream fs = new FileStream ( "C // file.txt", FileMode.OpenOrCreate, FileAccess.Write); StreamWriter m_streamWriter = new StreamWriter (fs); m_streamWriter. Flush (); // Write the content m_streamwriter.basestream.seek (0, seekorigin.begin); // write the contents of RichTextBox1 into file m_streamwriter.write (// Close this File m_streamwriter.flush (); m_StreamWriter.Close ();

From the above two code, the write data is easier than reading data. (3). How to implement print preview: Print preview is implemented by printing a preview dialog, implementing print previews for reading a text file, is to notify the contents of the file you want to preview to the Preview dialog. The following code is to display the content displayed in RichTextBox1, displayed by the Print Preview dialog:

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

The functions of its implementation are shown below:

Figure 02: Implementing a print preview for text files

(4). How to print files: Download a class "PrintDocument" in the name space "system.drawing.printing", you can trigger another event package in this name space by calling this "print" method " PRINTPAGE ". Set the documentation to be printed in this event to implement the print operation of the team text file. The following code is a "print" method that calls "PrintDocument", and calls the event "printpage" to print the content in RichTextBox1: TheprintDocument.print (); // Where theprintDocument is an object of the "PrintDocument" class The following code is setting printing SUMMARY i.e. the print RichTextBox1: float linesPerPage = 0; float yPosition = 0; int count = 0; float leftMargin = ev.MarginBounds.Left; float topMargin = ev.MarginBounds.Top; string line = null; Font printFont = richTextBox1 .Font; SolidBrush myBrush = new SolidBrush (Color.Black); // calculate how many lines of each printed page linesPerPage = ev.MarginBounds.Height / printFont.GetHeight (ev.Graphics); // StringReader reusable objects, the print richTextBox1 All content in While (count

Note: Since these types of local name spaces are eliminated in the above code, they must be successfully compiled and running the above code, they must import the namespace used in the program header.

three. Use a C # to handle the full source code for text files:

Mastering the key steps above, you can easily get a complete source program with C # to process text files, 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 InitializeComponent () in the Form InitializeComponent ();} // Clear Program PROTECTED OVERRIDE VOID DISPOSE (Bool Disposing) {if (disposing) {ix Components! = null) {components.dispose ();}} Base.dispose (Disposing);} private vid initiali zeComponent () {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.ancy = 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.Location = New Point (108, 288); Button3.Name = "Button3.Name =" Button3.Size = New Size (48, 30); Button3.taBindex = 2 Button3.Text = "Save"; 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 Settings"; Button4.Click = New System.EventHandler (Button4_Click); 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); this.This .Controls.add (button4); this.controls.add (button5); this.controls.add (richtextbox1); this.maximizebox = false; this.name = "form1"; this.text = "C # to manipulate text File "; this.ResumeLayout (false);} static void main () {Application.run (new form1 ());} private void button1_click (Object sender, system.eventargs e) {try {ix (OpenFileDialog1.showdialog () == DialogResult.OK) {FileStream fs = new FileStream (openFileDialog1.FileName, FileMode.Open, FileAccess.Read); StreamReader m_streamReader = new StreamReader (fs); // use StreamReader class to read the file m_streamReader.BaseStream.Seek ( 0, seekorigin.begin; // read each row from the data stream until the last line of the file, and display content this.richtextBox1.text = "in RichTextBox1, string strline = m_streamreader.readline (); while (Strline! = Null) {this.richtextbox1.text = strline "/ n"; strline = m_streamReader.readLine ();} // turn off this streamreader object m_streamReader.close ();}} catch (exception em) { Console.writeline (em.Message.toString ());

}}} Private void button3_click (object sender, system.eventargs e) {try {// Get Save the file name IF (SaveFileDialog1.ShowDialog () == DialogResult.ok) {// Create a file stream for writing or create a StreamWriter FileStream fs = new FileStream (@ saveFileDialog1.FileName, FileMode.OpenOrCreate, FileAccess.Write); StreamWriter m_streamWriter = new StreamWriter (fs); m_streamWriter.Flush (); // use StreamWriter dealings file written content m_streamWriter .Basestream.seek; // write the contents of RichTextBox1 into file m_streamwriter.write (richtextbox1.text); // Close this file 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 ();} // preview Print Document Private Void Button2_Click (Object Sender, System.EventArgs E) { try {string strText = richTextBox1.Text; 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 richTextBox1 content of private void button5_Click (object sender, System.EventArgs e) {printDialog1.Document = ThePrintDocument; string strText = richTextBox1.Text; 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; string line = null; Font printFont = richTextBox1.Font; SolidBrush myBrush = new SolidBrush (Color.Black); // calculate how many rows linesPerPage each page printed = Ev.marginbounds.height / printfont.getHeight (ev.graphics); // Repeat the StringReader object, print all content in RichTextBox1 While (count

Although this article only introduces the use of C # processing text files, there is still a lot of reference value for other files for C # processing, because the structure of the class defined in the name space "System.IO" and the structure and There are many structures that are used to handle the text files. I hope this article is helpful for file programming you use C #.

转载请注明原文地址:https://www.9cbs.com/read-107910.html

New Post(0)