如何读取文本文件内容:
在本文介绍的程序中,是把读取的文本文件,用一个richTextBox组件显示出来。要读取文本文件,必须使用到"StreamReader"类,这个类是由名字空间"System.IO"中定义的。通过"StreamReader"类的"ReadLine ( )"方法,就可以读取打开数据流当前行的数据了。下面代码实现的功能就是读取"C:\file.txt"并在richTextBox1组件中显示出来:
FileStream fs = new FileStream ( "C:\\file.txt"  , FileMode.Open , FileAccess.Read ) ;
    StreamReader m_streamReader = new StreamReader ( fs ) ;
  //使用StreamReader类来读取文件
  m_streamReader.BaseStream.Seek ( 0 , SeekOrigin.Begin ) ;
    // 从数据流中读取每一行,直到文件的最后一行,并在richTextBox1中显示出内容
    this.richTextBox1.Text = "" ;
    string strLine = m_streamReader.ReadLine ( ) ;
    while ( strLine != null )
    {
      this.richTextBox1.Text += strLine + "\n" ;
      strLine = m_streamReader.ReadLine ( ) ;
    }
    //关闭此StreamReader对象
    m_streamReader.Close ( ) ;

如何改变文本文件中数据内容:

在本文介绍的程序中,改变文本文件数据内容的功能是通过改变richTextBox1中的内容来实现的,当richTextBox1这的内容改变后,按动"另存为",就把richTextBox1中内容存储到指定的文本文件中了。要想改变文本文件内容,要使用到"StreamWriter"类,这个类和"StreamReader"一样,都是由"System.IO"名字空间来定义的。通过"StreamWriter"类的"Write ( )"方法,就可以轻松实现文本文件内容的更改了。下面代码的功能是:如果"C"盘存在"file.txt",则把richTextBox1中的内容写入到"file.txt"中,如果不存在,则创建此文件,然后在写入文本数据。

//创建一个文件流,用以写入或者创建一个StreamWriter
  FileStream fs = new FileStream ( "C\\file.txt"  , FileMode.OpenOrCreate , FileAccess.Write ) ;
    StreamWriter m_streamWriter = new StreamWriter ( fs ) ;
    m_streamWriter.Flush ( ) ;
    // 使用StreamWriter来往文件中写入内容
    m_streamWriter.BaseStream.Seek ( 0 , SeekOrigin.Begin ) ;
    // 把richTextBox1中的内容写入文件
    m_streamWriter.Write ( richTextBox1.Text ) ;
    //关闭此文件
    m_streamWriter.Flush ( ) ;
    m_streamWriter.Close ( ) ;

如何实现打印预览:

打印预览是通过打印预览对话框来实现的,实现对读取得文本文件的打印预览,最为重要的就是要通知打印预览对话框所要预览的文件的内容。下面代码就是把richTextBox1中显示的内容,通过打印预览对话框显示出来:
//www.naio.net
string strText = richTextBox1.Text ;
  StringReader myReader = new StringReader ( strText ) ;
  PrintPreviewDialog printPreviewDialog1 = new PrintPreviewDialog ( ) ;
  printPreviewDialog1.Document = ThePrintDocument  ;
  printPreviewDialog1.FormBorderStyle = FormBorderStyle.Fixed3D  ;
  printPreviewDialog1.ShowDialog ( ) ;  
下列代码是设定打印内容即打印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 ) ;
        //计算每一页打印多少行
      linesPerPage = ev.MarginBounds.Height / printFont.GetHeight ( ev.Graphics ) ;
        //重复使用StringReader对象 ,打印出richTextBox1中的所有内容
        while ( count < linesPerPage && ( ( line = myReader.ReadLine ( ) ) != null ) )
      {
// 计算出要打印的下一行所基于页面的位置
  yPosition = topMargin + ( count * printFont.GetHeight ( ev.Graphics ) ) ;
  // 打印出richTextBox1中的下一行内容
  ev.Graphics.DrawString ( line , printFont , myBrush , leftMargin , yPosition , new StringFormat ( ) ) ;
  count++ ;
        }
        // 判断如果还要下一页,则继续打印
        if ( line != null )
  ev.HasMorePages = true ;
        else
  ev.HasMorePages = false ;
        myBrush.Dispose ( ) ;
  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 ( )
  {
  //初始化窗体中的各个组件
  InitializeComponent ( ) ;
  }
  //清除程序中使用多的资源
  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 = "打开" ;
  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 = "预览" ;
  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 = "保存" ;
  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 = "打印机设置" ;
  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 = "打印" ;
  button5.Click += new System.EventHandler ( button5_Click ) ;
         saveFileDialog1.DefaultExt = "*.txt" ;
      saveFileDialog1.FileName = "file.txt" ;
  saveFileDialog1.InitialDirectory = "c:\\" ;
  saveFileDialog1.Title = "另存为!" ;
  openFileDialog1.DefaultExt = "*.txt" ;
  openFileDialog1.FileName = "file.txt" ;
  openFileDialog1.InitialDirectory = "c:\\" ;
  openFileDialog1.Title = "打开文本文件!" ;
  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#来操作文本文件" ;
  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 ) ;
  //使用StreamReader类来读取文件
  m_streamReader.BaseStream.Seek ( 0 , SeekOrigin.Begin ) ;
    // 从数据流中读取每一行,直到文件的最后一行,并在richTextBox1中显示出内容
    this.richTextBox1.Text = "" ;
    string strLine = m_streamReader.ReadLine ( ) ;
    while ( strLine != null )
    {
      this.richTextBox1.Text += strLine + "\n" ;
      strLine = m_streamReader.ReadLine ( ) ;
    }
    //关闭此StreamReader对象
    m_streamReader.Close ( ) ;
  }
      }
      catch ( Exception em )
        {
  Console.WriteLine ( em.Message.ToString ( ) ) ;
        }
  
  }
  
  private void button3_Click ( object sender , System.EventArgs e )
  {
        try
        {
  //获得另存为的文件名称
  if ( saveFileDialog1.ShowDialog ( ) == DialogResult.OK )
  {
  //创建一个文件流,用以写入或者创建一个StreamWriter
  FileStream fs = new FileStream ( @saveFileDialog1.FileName  , FileMode.OpenOrCreate , FileAccess.Write ) ;
    StreamWriter m_streamWriter = new StreamWriter ( fs ) ;
    m_streamWriter.Flush ( ) ;
  
    // 使用StreamWriter来往文件中写入内容
    m_streamWriter.BaseStream.Seek ( 0 , SeekOrigin.Begin ) ;
    // 把richTextBox1中的内容写入文件
    m_streamWriter.Write ( richTextBox1.Text ) ;
    //关闭此文件
    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 ( ) ;
  }
  //预览打印文档
  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 ( ) ) ;
        }
  }
  //打印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 ) ;
        //计算每一页打印多少行
      linesPerPage = ev.MarginBounds.Height / printFont.GetHeight ( ev.Graphics ) ;
        //重复使用StringReader对象 ,打印出richTextBox1中的所有内容
        while ( count < linesPerPage && ( ( line = myReader.ReadLine ( ) ) != null ) )
      {
// 计算出要打印的下一行所基于页面的位置
  yPosition = topMargin + ( count * printFont.GetHeight ( ev.Graphics ) ) ;
  // 打印出richTextBox1中的下一行内容
  ev.Graphics.DrawString ( line , printFont , myBrush , leftMargin , yPosition , new StringFormat ( ) ) ;
  count++ ;
        }
        // 判断如果还要下一页,则继续打印
        if ( line != null )
  ev.HasMorePages = true ;
        else
  ev.HasMorePages = false ;
        myBrush.Dispose ( ) ;
   }
}

使用c#操作txt的更多相关文章

  1. python操作txt文件中数据教程[4]-python去掉txt文件行尾换行

    python操作txt文件中数据教程[4]-python去掉txt文件行尾换行 觉得有用的话,欢迎一起讨论相互学习~Follow Me 参考文章 python操作txt文件中数据教程[1]-使用pyt ...

  2. python操作txt文件中数据教程[3]-python读取文件夹中所有txt文件并将数据转为csv文件

    python操作txt文件中数据教程[3]-python读取文件夹中所有txt文件并将数据转为csv文件 觉得有用的话,欢迎一起讨论相互学习~Follow Me 参考文献 python操作txt文件中 ...

  3. python操作txt文件中数据教程[2]-python提取txt文件

    python操作txt文件中数据教程[2]-python提取txt文件中的行列元素 觉得有用的话,欢迎一起讨论相互学习~Follow Me 原始txt文件 程序实现后结果-将txt中元素提取并保存在c ...

  4. python操作txt文件中数据教程[1]-使用python读写txt文件

    python操作txt文件中数据教程[1]-使用python读写txt文件 觉得有用的话,欢迎一起讨论相互学习~Follow Me 原始txt文件 程序实现后结果 程序实现 filename = '. ...

  5. C#操作txt文件并清空添加操作

    C#操作txt文件,进行清空添加操作的例子.代码: //把txt清空 FileStream stream = File.Open(Adr,FileMode.OpenOrCreate,FileAcces ...

  6. python 操作txt 生成新的文本数据

    name: Jack ; salary: 12000 name :Mike ; salary: 12300 name: Luk ; salary: 10030 name :Tim ; salary: ...

  7. QTP操作txt文档

    QTP可以在txt文件(文本文件中读取数据) 首先创造一个文档对象 set fso = createObject("scripting.filesystemobject") 然后用 ...

  8. C#操作txt文件

    目的:txt文件的创建,读写操作 功能:创建一个winform窗体,当文件不存在时可以实现txt文件的创建 效果: 代码: 文件的创建(判断文件是否存在,不存在则创建新的文本文件): private ...

  9. c#操作txt

    C#追加文件 StreamWriter sw = File.AppendText(Server.MapPath(".")+"\\myText.txt"); sw ...

  10. java操作txt文本(一):遇到指定字符换行

    想法由来:有时查看网页源代码的css文件内容,竟是恼人的压缩后代码(不换行),如下图所示-- 它的可读性很差,所以写了下面这个简单的程序,实现自动换行. 适用条件:遇到指定字符换行(本例中遇到'}'换 ...

随机推荐

  1. Postgresql在线备份和恢复

    1.实验环境 OS: RedHat Linux Enterprisedb 6.3 DB: postgresql 9.3 PGHOME: /opt/PostgreSQL/9.3 PGDATA: /opt ...

  2. 关于http与https区别

    http与https: http叫超文本传输协议,信息为明文传输.https是具有安全性的传输协议,是由http+ssl层,需要到ca申请证书,一般需要费用.信息为加密传输,需要验证用户身份.二者的端 ...

  3. DevOps之虚拟专用网络VPN

    唠叨话 关于德语噢屁事的知识点,仅提供专业性的精华汇总,具体知识点细节,参考教程网址,如需帮助,请留言. <虚拟专用网络VPN(Virtual Private Network)> 关于虚拟 ...

  4. C#利用String类的IndexOf、LastIndexOf、Substring截取字符串

    一.String.IndexOf String.IndexOf 方法 (Char, Int32, Int32)报告指定字符在此实例中的第一个匹配项的索引(从0开始).搜索从指定字符位置开始,并检查指定 ...

  5. 前端笔记----jquery入门知识点总结

    一.jquery的加载方法 $(document).ready(function(){js代码}); $(function(){js代码});(一般使用这个); 注意点1:使用jquery必须先导入函 ...

  6. (10.20)Java小作业!

    今天想要和大家分享一道我最近遇到的题,里面既包括了嵌套循环的运用,还有函数的定义与调用,我个人觉得挺有价值的. 打印一个由*号构成的等腰三角形: 具体的解题方法如下: public class get ...

  7. 解决Ubuntu中phpmyadmin对数据上传上限2M

    本文部分参考自:http://www.myhack58.com/Article/sort099/sort0102/2011/29396.htm 原文有少量错误或者过时的(相对于ubuntu15来说)内 ...

  8. hash在URL上的用法及作用

    阅读目录 1. # 2. ? 3. & 回到顶部 1. # 10年9月,twitter改版.一个显著变化,就是URL加入了"#!"符号.比如,改版前的用户主页网址为http ...

  9. 【转】 bio 与块设备驱动

    原文地址: bio 与块设备驱动      系统中能够随机访问固定大小数据片(chunk)的设备被称作块设备,这些数据片就称作块.块设备文件都是以安装文件系统的方式使用,此也是块设备通常的访问方式.块 ...

  10. LINUX 笔记-ubuntu 配置 jdk 环境

    在 /etc/profile 文件尾添加 JAVA_HOME=/opt/jdk1.8.0JRE_HOME=${JAVA_HOME}/jre   PATH=$PATH:$HOME/bin:$JAVA_H ...