文件读写操作

StreamReader sr = ``new StreamReader(path); ``//path是要读取的文件的完整路径

图片 1图片 2Code
using System;
using System.IO;
/*从文本文件中读或者写文本时,首先需创建一个与文件相关的StreamReader或者StreamWriter对象
 每一个StreamReader或StreamWriter对象都与一种字符编码方式相关。默认UTF8Encoding
*/
class FileOperate
{
    public static  string content=””;
    public static  StreamReader sr=null;
    public static StreamWriter sw=null;
    //读取文本时,有许多方法可以创建与文件名相关的Streamreader对象   
    /// <summary>
    ///方法一: 从文件名直接创建
    /// </summary>
    public void ReadFromFileName()
    {
        
        try
        {
            sr=new StreamReader (“TestFile.txt”);
            string txt=””;
            while((txt=sr.ReadLine())!=null)
            {
                content+=txt;
            }
            Console.WriteLine (“—-ReadFromFileName——“);
            Console.WriteLine (content);
        }
        catch(Exception ex)
        {
            Console.WriteLine (ex.Message);
        }
        finally
        {
            sr.Close ();
        }
        
    }
    /// <summary>
    ///方法二: 使用File类或者FileInfo类的OpenText方法创建
    /// </summary>
    public void ReadUseFileOrFileInfo()
    {
        
        try
        {
         FileInfo fi=new FileInfo (“TestFile.txt”);
         sr=fi.OpenText();
         content=””;
         while(!sr.EndOfStream)
         {
            content+=sr.ReadLine();
         }
            Console.WriteLine (“—-ReadUseFileOrFileInfo——“);
            Console.WriteLine (content);        
        }
        catch(Exception ex)
        {
            Console.WriteLine (ex.Message);
        }
        finally
        {
            sr.Close ();
        }
        
    }
    
    /// <summary>
    /// 方法3:通过FileStream对象创建
    /// </summary>
    public void ReadThroughFileStream()
    {
        //打开文件 只读
        FileStream fs1=new FileStream(“TestFile.txt”,FileMode.Open,FileAccess.Read );
        //打开文件 读写
        //FileStream fs2=File.Open (“TestFile.txt”,FileMode.Open ,FileAccess.ReadWrite);
        //打开文件 读写
        //FileStream fs3=File.Create(“TestFile.txt”);
        //打开文件 只读
        //FileStream fs4=File.OpenRead(“TestFile.txt”);
            
        try
        {
         sr=new StreamReader (fs1);
         content=””;
         while(!sr.EndOfStream)
         {
            content+=sr.ReadLine();
         }
         Console.WriteLine (“—-ReadThroughFileStream——“);
         Console.WriteLine (content);    
        }
        catch(Exception ex)
        {
          Console.WriteLine (ex.Message);
        }
        finally
        {
            fs1.Close ();
            sr.Close ();
        }
    }
    //写入文件 三种方式
    /// <summary>
    /// 方法一:通过文件名创建
    /// </summary>
    public void WriteFromFileName()
    {
        try
        {
            sw=new StreamWriter(“TestFile.txt”);
            Console.WriteLine (“Input Write File’s Content:”);
            string lines=Console.ReadLine ();
            sw.WriteLine(lines);
        }
        catch(Exception ex)
        {
            Console.WriteLine (ex.Message );
        }
        finally
        {
            sw.Close ();
        }
    }
    /// <summary>
    /// 文件写入方法二:使用File类或者FileInfo类的CreateText或AppendText方法来创建
    /// AppendText方法:对于文件内容进行追加 CreateText方法:会删除已经存在的文件
    /// 缺点:只能创建支持UTF8Encoding的StreamWriter对象
    /// </summary>
    public void WriteUseFileOrFileInfo()
    {
      //File类的CreateText方法
      StreamWriter sw1=File.CreateText(“TestFile.txt”);
      sw1.WriteLine(“File类的CreateText方法”);
      sw1.Close ();
     //FileInfo CreateText 
      FileInfo fi1=new FileInfo (“TestFile.txt”);
      StreamWriter sw2=fi1.CreateText();
      sw2.WriteLine(“FileInfo CreateText “);
      sw2.Close ();
      //File类的AppendText方法
      StreamWriter sw3=File.AppendText(“TestFile.txt”);
      sw3.WriteLine(“File类的AppendText方法”);
      sw3.Close ();
      //FileInfo 的AppendText
      FileInfo fi2=new FileInfo (“TestFile.txt”);
      StreamWriter sw4=fi2.AppendText();
      sw4.WriteLine(“FileInfo 的AppendText”);
      sw4.Close ();
    }
    /// <summary>
    /// 通过FileStream对象来创建
    /// </summary>
    public void WriteThroughFileStream()
    {
    
        //打开文件 只写
        FileStream fs1=new FileStream(“TestFile.txt”,FileMode.Open,FileAccess.Write);
        StreamWriter sw1=new StreamWriter(fs1);
        sw1.WriteLine(“通过FileStream对象来创建”);      
        sw1.Close ();
        fs1.Close ();
        //打开文件 读写
        FileStream fs2=File.Open (“TestFile.txt”,FileMode.Open ,FileAccess.ReadWrite);
        StreamWriter sw2=new StreamWriter(fs2);
        sw2.WriteLine(“通过File.Open创建FileStream对象”);       
        sw2.Close ();
        fs2.Close ();
        //打开文件 读写
        FileStream fs3=File.Create(“TestFile.txt”);
        StreamWriter sw3=new StreamWriter(fs3);
        sw3.WriteLine(“通过File.Create创建FileStream对象”);              
        sw3.Close ();
        fs3.Close ();
        //打开文件 只写
        FileStream fs4=File.OpenWrite(“TestFile.txt”); 
        StreamWriter sw4=new StreamWriter(fs4);
        sw4.WriteLine(“通过File.OpenWrite创建FileStream对象”);            
        sw4.Close ();
        fs4.Close ();
    }
    
    /// <summary>
    /// 二进制文件读写
    /// </summary>
    
    public void ByteReadWrite()
    {
             FileStream fs = new FileStream(“TestFile.txt”, FileMode.OpenOrCreate, FileAccess.ReadWrite);//创建文件 
             StreamWriter sw = new StreamWriter(fs);
              // 以文本方式写一个文件
             sw.WriteLine(“Hello, World”);
             sw.WriteLine(“你好吗?”);
             sw.WriteLine(“我很好!”);
             sw.WriteLine(“嘿嘿,示例好傻!”);
             sw.Flush();     //清理缓冲区
            StreamReader sr = new StreamReader(fs);
            sr.BaseStream.Seek(0, SeekOrigin.Begin);//定位到流的开始位置 
            string str=string.Empty;
            while (!sr.EndOfStream)  //未到文件流结尾
            {
                 str+= sr.ReadLine();
            }
            BinaryReader br = new BinaryReader(fs);
            br.BaseStream.Seek(0, SeekOrigin.Begin);//定位到流的开始位置 
            Byte b = new Byte();
            while (br.PeekChar() > -1)//定位到下一个字符
            {
                b += br.ReadByte();
            }
             //关闭文件流
             sw.Close();
             br.Close();
             sr.Close();
             fs.Close();

String str_read = sr.ReadToEnd(); ``//从开始到末尾读取文件的所有内容,str_read 存放的就是读取到的文本

   }
    
    public static void Main(string[] args)
    {
        FileOperate ofile=new FileOperate();
        //读取文件写入文件                
        ofile.WriteFromFileName();
        ofile.ReadFromFileName();
        ofile.WriteUseFileOrFileInfo();
        ofile.ReadUseFileOrFileInfo();
        ofile.WriteThroughFileStream();
        ofile.ReadThroughFileStream();
        ofile.ByteReadWrite();
        Console.ReadLine();
    }

sr.Close(); ``//读完文件记得关闭流

}

 

如果要一条一条读

while ((content = sr.ReadLine()) != null)//按行输出
{
f+=content;
}

写入文档方法

//FileMode.Append为不覆盖文件效果.create为覆盖
FileStream fs = new FileStream(path, mode: FileMode.Append);
StreamWriter sw = new StreamWriter(fs);
//开始写入

sw.Write(“xxxxx”);
//清空缓冲区
sw.Flush();
//关闭
sw.Close();
fs.Close();