Text files are a common file format, so how to process text files becomes a focus of programming. This article will discuss how C # is used to process text files. The content focuses on how to read the content of a text file, how to change the content of a text file, and how to use C # To print, preview, and print the read text file.
I. This articleProgramDesign and run the software environment:
(1). Microsoft Windows 2000 Server Edition
(2). Net Framework SDK beta 2
II. C # important processes for processing text files:
(1). How to read text file content:
In the program described in this article, the read text file is displayed using a RichTextBox component. To read a text file, you must use the "streamreader" class, which is defined in the namespace "system. Io. You can use the "Readline ()" method of the "streamreader" class to read the data from the current row of the data stream. Below Code The function 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 the streamreader class to read files
M_streamreader.basestream.seek (0, seekorigin. Begin );
// Read each row from the data stream until the last row of the file is displayed in richtextbox1.
This. richtextbox1.text = "";
String strline = m_streamreader.readline ();
While (strline! = NULL)
{
This. richtextbox1.text + = strline + "\ n ";
Strline = m_streamreader.readline ();
}
// Close this streamreader object
M_streamreader.close ();
(2). How to change the data content in a text file:
In the program described in this article, the function of changing the data content of a text file is implemented by changing the content in richtextbox1. When the content in richtextbox1 changes, press "Save ", the content in richtextbox1 is stored in the specified text file. To change the content of a text file, you must use the "streamwriter" class. This class, like "streamreader", is defined by the "system. Io" namespace. With the "write ()" method of the "streamwriter" class, you can easily change the content of a text file. The function of the following code is: if "C" disk has "file.txt", write the content in richtextbox1 to "file.txt". If it does not exist, create this file, then, write text data.
// Create a file stream for writing or creating a streamwriter
Filestream FS = new filestream ("C \ file.txt", filemode. openorcreate, fileaccess. Write );
Streamwriter m_streamwriter = new streamwriter (FS );
M_streamwriter.flush ();
// Use streamwriter to write content to files
M_streamwriter.basestream.seek (0, seekorigin. Begin );
// Write the content in richtextbox1 to the file
M_streamwriter.write (richtextbox1.text );
// Close this file
M_streamwriter.flush ();
M_streamwriter.close ();
From the above two codes, writing data is easier than reading data.
(3) how to print and preview:
Print preview is implemented through the print preview dialog box. To print and preview a text file after reading, the most important thing is to notify the print preview dialog box of the content of the file to be previewed. The following code displays the content displayed in richtextbox1 in the print preview dialog box:
In the namespace "system. drawing. printing "defines a class" printdocument ". By calling the" print "method of this class, another event" printpage "encapsulated in this namespace can be triggered ". In this event, set the document content to be printed to print the team text file. The following code calls the "print" method of "printdocument" and calls the event "printpage" to print the content in richtextbox1:
Theprintdocument. Print (); // Where theprintdocument is an object of the "printdocument" Class
Run the following code to print the printed content in 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 the number of rows printed per page
Linesperpage = eV. marginbounds. Height/printfont. getheight (EV. Graphics );
// Repeat the stringreader object to print all the content in richtextbox1
While (count <linesperpage & (line = myreader. Readline ())! = NULL ))
{
// Calculate the location of the page on which the next row is to be printed
Yposition = topmargin + (count * printfont. getheight (EV. Graphics ));
// Print the content of the next line in richtextbox1
Ev. Graphics. drawstring (line, printfont, mybrush, leftmargin, yposition, new stringformat ());
Count ++;
}
// Determine whether to print the next page.
If (line! = NULL)
Ev. hasmorepages = true;
Else
Ev. hasmorepages = false;
Mybrush. Dispose ();
Note: Because the namespace for these classes is saved in the above Code, to successfully compile and run the above Code, you must import the namespace used in the program header.
3. Use C # to process the complete source code (control. CS) of a text file ):
After mastering these key steps, you can easily get a complete source program that uses C # To process text files. The details are 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 ()
{
// Initialize components in the form
Initializecomponent ();
}
// Clear multiple resources in the program
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 (button#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 = "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.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! ";
Openfiledialog1.defaultext = "*. txt ";
Openfiledialog1.filename = "file.txt ";
Openfiledialog1.initialdirectory = "C :\\";
Openfiledialog1.title = "open a 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 #. Composition This document ";
This. resumelayout (false );
}
Static void main ()
{
Application. Run (New form1 ());
}
Private void button#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 files
M_streamreader.basestream.seek (0, seekorigin. Begin );
// Read each row from the data stream until the last row of the file is displayed in richtextbox1.
This. richtextbox1.text = "";
String strline = m_streamreader.readline ();
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
{
// Obtain the name of the file to be saved
If (savefiledialog1.showdialog () = dialogresult. OK)
{
// Create a file stream for writing or creating a streamwriter
Filestream FS = new filestream (@ savefiledialog1.filename, filemode. openorcreate, fileaccess. Write );
Streamwriter m_streamwriter = new streamwriter (FS );
M_streamwriter.flush ();
// Use streamwriter to write content to files
M_streamwriter.basestream.seek (0, seekorigin. Begin );
// Write the content in richtextbox1 to the 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 and print the 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 the content in richtextbox1
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 the number of rows printed per page
Linesperpage = eV. marginbounds. Height/printfont. getheight (EV. Graphics );
// Repeat the stringreader object to print all the content in richtextbox1
While (count <linesperpage & (line = myreader. Readline ())! = NULL ))
{
// Calculate the location of the page on which the next row is to be printed
Yposition = topmargin + (count * printfont. getheight (EV. Graphics ));
// Print the content of the next line in richtextbox1
Ev. Graphics. drawstring (line, printfont, mybrush, leftmargin, yposition, new stringformat ());
Count ++;
}
// Determine whether to print the next page.
If (line! = NULL)
Ev. hasmorepages = true;
Else
Ev. hasmorepages = false;
Mybrush. Dispose ();
}
}
Iv. Summary:
Although this article only introduces how to use C # To process text files, it also has a lot of reference value for C # To process other files, because it is in the namespace "system. the structure of classes defined in Io to process other files and the structure of classes used to process text files are many of the same. I hope this article will help you program files using C.
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