C Implements Summary of Text File Reading and Writing Methods

  • 2021-06-29 11:49:19
  • OfStack

Method 1:


using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;
 
namespace txt
{
  public partial class Form1 : Form
  {
    // string path;
    public Form1()
    {
      InitializeComponent();
      button3.Click+=button3_Click;
    }
 
    private void textBox2_TextChanged(object sender, EventArgs e)
    {
      string path1 = textBox2.Text;
      if(!File.Exists(path1))
      {
        MessageBox.Show(" file does not exist ");
      }
    }
    // Browse button 
    private void button3_Click(object sender, EventArgs e)
    {
      /*if (folderBrowserDialog1.ShowDialog() == DialogResult.OK)
      {
 
        string selUrl = folderBrowserDialog1.SelectedPath;
      }*/
     
     OpenFileDialog ofd = new OpenFileDialog();
 
      if (ofd.ShowDialog() == DialogResult.OK)
      {
        textBox2.Text = ofd.FileName;
      }
 
      // Select Folder 
      /* FolderBrowserDialog fbd = new FolderBrowserDialog();
      fbd.ShowDialog();
      MessageBox.Show(fbd.SelectedPath);
       */
    }
    // read file 
    private void button1_Click(object sender, EventArgs e)
    {
      if(textBox2.Text!=null)
        // Read the contents of the file and display it textbox1 Medium for user modification  
      {
        string path=textBox2.Text;
        if (File.Exists(path))
       //  {
        //   File.Delete(path);
        // }
        textBox1.Text = File.ReadAllText(path, Encoding.Default);
      }
    }
 
    private void button2_Click(object sender, EventArgs e)
    {
      // string[] appendText=textBox1.Text;
       
      File.WriteAllText(textBox2.Text, textBox1.Text, Encoding.Default);
      MessageBox.Show(" Save Successfully ");
    }

  }
}

Method 2:


namespace 文本文件打开测试 
{ 
 public partial class Form1 : Form 
 { 
  public Form1() 
  { 
   InitializeComponent(); 
  } 
  private void btn_Read_Click(object sender, EventArgs e) 
  { 
   //异常检测开始 
   try
   { 
    FileStream fs = new FileStream(@tB_PachFileName.Text , FileMode.Open, FileAccess.Read);//读取文件设定 
    StreamReader m_streamReader = new StreamReader(fs, System.Text.Encoding.GetEncoding("GB2312"));//设定读写的编码 
    //使用StreamReader类来读取文件 
    m_streamReader.BaseStream.Seek(0, SeekOrigin.Begin); 
    // 从数据流中读取每1行,直到文件的最后1行,并在rTB_Display.Text中显示出内容 
    this.rTB_Display.Text = ""; 
    string strLine = m_streamReader.ReadLine(); 
    while (strLine != null) 
    { 
     this.rTB_Display.Text += strLine + "\n"; 
     strLine = m_streamReader.ReadLine(); 
    } 
    //关闭此StreamReader对象 
    m_streamReader.Close(); 
   } 
   catch
   { 
    //抛出异常 
    MessageBox.Show("指定文件不存在"); 
    return; 
   } 
   //异常检测结束 
  } 
  private void btn_Replace_Click(object sender, EventArgs e) 
  { 
   //判断替换开始 
   if (tB_Replace.Text == ""&&tB_Replace_2.Text=="") 
   { 
    MessageBox.Show("想替换的字符都没有就换啊,你太有才了"); 
   } 
   else
   { 
    if (rTB_Display.Text == "") 
    { 
     MessageBox.Show("文件内容为空无法进行替换,请检查文件"); 
    } 
    else
    { 
     string str = rTB_Display.Text.ToString(); 
     rTB_Display.Text = str.Replace(@tB_Replace.Text ,@tB_Replace_2.Text);//替换 
    } 
   } 
   //结束 
  } 
  private void btn_Save_Click(object sender, EventArgs e) 
  { 
   //异常检测开始 
   try
   { 
    //创建1个文件流,用以写入或者创建1个StreamWriter 
    FileStream fs = new FileStream(@tB_Save.Text, 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(rTB_Display.Text); 
    //关闭此文件 
    m_streamWriter.Flush(); 
    m_streamWriter.Close(); 
   } 
   catch
   { 
    //抛出异常 
    MessageBox.Show("写入文件失败,请检查路径 文件名与权限是否符合"); 
   } 
   //异常检测结束 
  } 
 } 
}

Method 3:


// Write to Text File 
  class WriteTextFile
  {
    static void Main()
    {
      // If the file does not exist, it is created;Overwrite if present 
      // This method writes character array wrapping display 
      string[] lines = { "first line", "second line", "third line"," No. 4 That's ok " };
      System.IO.File.WriteAllLines(@"C:\testDir\test.txt", lines, Encoding.UTF8);

      // If the file does not exist, it is created;Overwrite if present 
      string strTest = " This example test 1 Strings written to a text file. ";
      System.IO.File.WriteAllText(@"C:\testDir\test1.txt", strTest, Encoding.UTF8);

      // Processing lines of text before writing it to a file 
      //StreamWriter1 Default override of parameters 
      //StreamWriter No. 2 Parameters are false Overwrite the existing file for true Append text to the end of the file 
      using (System.IO.StreamWriter file = new System.IO.StreamWriter(@"C:\testDir\test2.txt",true))
      {
        foreach (string line in lines)
        {
          if (!line.Contains("second"))
          {
            file.Write(line);// Append the end of the file directly without breaking lines 
            file.WriteLine(line);//  Append end end end of file directly, wrap   
          }
        }
      }
    }
  }

// Read Text File 

  class ReadTextFile
  {
    static void Main()
    {
      // Read String Directly 
      string text = System.IO.File.ReadAllText(@"C:\testDir\test1.txt");
      Console.WriteLine(text);

      // Read as String Array by Line 
      string[] lines = System.IO.File.ReadAllLines(@"C:\testDir\test.txt");
      foreach (string line in lines)
      {
        Console.WriteLine(line);
      }

      // Read text files stream from beginning to end 
      // This method will 1 That's ok 1 Line Read Text 
      using (System.IO.StreamReader sr = new System.IO.StreamReader(@"C:\testDir\test.txt"))
      {
        string str;
        while ((str = sr.ReadLine()) != null)
        {
          Console.WriteLine(str);
        }
      }
      Console.Read();
    }
  }

The above is the whole content of this article, I hope you like it.


Related articles: