c#中的流类

该博客主要展示了C#中文件和流的操作。包含文件定位、文件流读写、定位方法、设置流长度、文本流读写、内存流、缓冲流、字符串读写器、二进制读写以及读取Web页面等操作,还给出了相应的代码示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

using System;
using System.IO;
using System.Text;
using System.Net;
namespace ConsoleApplication1
{
 /// <summary>
 /// ReadomReadFile 的摘要说明。
 /// </summary>
 public class ReadomReadFile
 {
  static FileStream fs = null;
  static StreamWriter sw = null;
  static StreamReader sr = null;
        static MemoryStream ms = null;
  static BufferedStream bs = null;
  static StringWriter strW = null;
  static StringReader strR = null;

  static byte[] ba = null;
  static string str = "";
  

  //文件定位
  static void FromBegin()
  {
   try
   {
    fs = new FileStream("d://test.txt",FileMode.Open);
    if(fs.CanSeek)
    {
     fs.Seek(3,SeekOrigin.Begin);
                 int i = fs.ReadByte();
     System.Console.WriteLine("4 bytes from Begin is :{0}",(char)i);
    }
   }
   finally
   {
    fs.Close();
   }
  }
  //文件流
  public static void FileS()
  {
   ba = new byte[]{76,101,116,32,116,104,101,114,101,32,98,101,32,108,105,103,104,116};
   fs = new FileStream("d://test.txt",FileMode.OpenOrCreate);
   fs.Write(ba,0,ba.Length);
   fs.Close();
   fs =  new FileStream("d://test.txt",FileMode.Open);
   int i;
   
   if(fs.CanRead)
   {
    for(i = 0; (i=fs.ReadByte())!= -1; i++)
    {
     str += (char)i;
    }
    fs.Flush();
    Console.WriteLine(str);
   }
  }
  //定位方法
  public static void SeekMethod()
  {
   
   ba = new byte[]{97,112,112,108,101,115,97,117,99,101};
   fs = new FileStream("d://test.txt",FileMode.Open);
   fs.Write(ba,0,ba.Length);
   Console.WriteLine("Lentth:{0},Position:{1}",fs.Length,fs.Position);
   if(fs.CanRead)
   {
    fs.Seek(13,SeekOrigin.Begin);
    Console.WriteLine("Position:{0}",fs.Position);
    fs.Write(ba,0,ba.Length);
   }
   str = "";
   fs.Seek(0,SeekOrigin.Begin);
   for(int i = 0; (i = fs.ReadByte())!=-1; i++)
   {
    str += (char)i;
   }
   Console.WriteLine(str);
   
  }
  static void SeekSetLenth()
  {
   ba = new byte[]{32,97,110,100,32,112,101,97,114,115};
   fs = new FileStream("d://test.txt",FileMode.Append,FileAccess.Write);
   fs.Write(ba,0,ba.Length);
   fs.Close();

   fs = new FileStream(@"d:/test.txt",FileMode.Open);
   str = "";
   //设置流的长度
   fs.SetLength(fs.Length -5);
   for(int i = 0;(i=fs.ReadByte())!=-1; i++)
   {
    str += (char)i;
   }
   Console.WriteLine(str);
   fs.Close();
  }
  //文本流的读与写
  public static void ReadWrite()
  {
   fs = new FileStream("d://test.txt",FileMode.OpenOrCreate);
   sw = new StreamWriter(fs);
   sw.WriteLine("Hello World");
   sw.Close();
   fs = new FileStream("d://test.txt",FileMode.Open);
   //编码方式
//   StreamReader r = new StreamReader(fs,System.Text.Encoding.BigEndianUnicode);
//   StreamReader r = new StreamReader(fs,System.Text.Encoding.ASCII);
//   StreamReader r = new StreamReader(fs,System.Text.Encoding.Unicode);
   //这一个可以正常显示字节流
//   StreamReader r = new StreamReader(fs,System.Text.Encoding.UTF7)
   //这一个可以正常显示字节流
    sr = new StreamReader(fs,System.Text.Encoding.UTF8);
   str = "";


   while((str  = sr.ReadLine())!= null)
   {
    Console.WriteLine(str);
   }
   sr.Close();
  }
  //内存流
  public static void MemStream()
  {
   ms = new MemoryStream(64);
   Console.WriteLine("Lenth:{0}/tPosition:{1}/tCapacity:{2}",ms.Length,ms.Position,ms.Capacity);
   Console.WriteLine("Contents:");
   for(int i = 0; i < 64; i++)
   {
    ms.WriteByte((byte)i);
   }
   Console.WriteLine("Lenth:{0}/tPosition:{1}/tCapacity:{2}",ms.Length,ms.Position,ms.Capacity);
   Console.WriteLine("Contents:");
   byte[] ba = ms.GetBuffer();
   foreach(byte b in ba)
   {
    try
    {
     //注意-3
     Console.Write("{0,-3}",b);
    }
    catch(Exception e)
    {
     System.Console.WriteLine(e.Message);
    }
    finally
    {
//     m.Close();
    }
   }
    //流已经达到最大容量,再向它里面添加东西,会动态的改变容量大小
   str = "foo";
   for(int i = 0; i < 3; i++)
   {
    ms.WriteByte((byte)str[i]);
   }
   Console.WriteLine("Lenth:{0}/tPosition:{1}/tCapacity:{2}",ms.Length,ms.Position,ms.Capacity);
   //将此内存流写入一个文件流
   fs = new FileStream("d:/test.txt",FileMode.OpenOrCreate,FileAccess.Write);
   ms.WriteTo(fs);
   ms.Close();
  }
  //BufferedStream:此与内存流做一样的内容
  public static void BufStream()
  {
   fs = new FileStream("d:/test.txt",FileMode.OpenOrCreate,FileAccess.ReadWrite);
   bs = new BufferedStream(fs);
   Console.WriteLine("Lenth:{0}/tPosition:{1}",bs.Length,bs.Position);
   Console.WriteLine("/nContent:");
   ba = new byte[bs.Length];
   bs.Position = 0;
   bs.Read(ba,0,(int)bs.Length);
   foreach (byte b in ba)
   {
    Console.Write("{0,-5}",b);
   }
   str = "foo";
   for (int i = 0; i < 3; i++)
   {
    bs.WriteByte((byte)str[i]);
   }
   Console.WriteLine("Lenth:{0}/tPosition:{1}",bs.Length,bs.Position);
   for(int i = 0; i <(256-67)+1;i++)
   {
    bs.WriteByte((byte)i);
   }
   Console.WriteLine("Lenth:{0}/tPosition:{1}",bs.Length,bs.Position);
   bs.Close();
  }
  //字符串读写器与写入器
  public static void StringReaderWrite()
  {
   strW = new StringWriter();
   strW.WriteLine("String a song of {0} pence", 6);
   str = "A pocket full of rye";
   strW.Write(str);
   //NewLine
   strW.WriteLine(strW.NewLine);
   strW.Write(new StringBuilder("baked in a pie"));
   strW.WriteLine();
   //strW.Close();
   Console.WriteLine(strW);
   //**********************************************
   StringBuilder sb = strW.GetStringBuilder();
   int i = sb.Length;
   sb.Append("The birds began to sing");
   sb.Insert(i,"When the pie was opened/n");
   sb.AppendFormat("/n Wasn't that a {0} to set before the King","dainty dish");
   Console.WriteLine(strW);
            //**********************************************
   Console.WriteLine("************StringReader***************");
   strR  = new StringReader(strW.ToString());
   str = strR.ReadLine();
   Console.WriteLine(str);
   Console.Write((char)strR.Read());
   char[] ca = new char[37];
   strR.Read(ca,0,19);
   Console.Write(ca);
   Console.WriteLine(strR.ReadToEnd());
   //***********************************************
   Console.WriteLine();
   StringReader r = new StringReader(strW.ToString());
   str = strR.ReadLine();
            Console.WriteLine(str);
   Console.Write((char)strR.Read());
   ca = new char[37];
   Console.Write(ca);
   strR.ReadBlock(ca,0,37);
   Console.Write(ca);
   Console.WriteLine(strR.ReadToEnd());
   strR.Close();
            strW.Close();
  }
  static void BinReadWrite()
  {
   //文本写
   fs = new FileStream("d:/test.txt",FileMode.OpenOrCreate);
   sw = new StreamWriter(fs);
   sw.Write("Hello World");
   sw.Write(123);
   sw.Write(' ');
   sw.Write(45.67);
   sw.Close();
   fs.Close();
            //二进制写
   fs = new FileStream("d:/test.txt",FileMode.OpenOrCreate);
   BinaryWriter bw = new BinaryWriter(fs);
   bw.Write(123);
   bw.Write(' ');
   bw.Write(45.67);
   //二进制读
   bw.BaseStream.Position = 0;
   BinaryReader br = new BinaryReader(fs);
   int i = 0;
   while(true)
   {
    i = bw.BaseStream.ReadByte();
    if(-1 == i)
    {
     Console.WriteLine();
     break;
    }
    Console.Write("{0,-4}",i);
   }
   bw.Close();
   sw.Close();
   fs.Close();
   
  }
  //读取Web页面
  public static void WebPage()
  {
   str = "http://www.microsoft.com";
   Uri uri = new Uri(str);
   WebRequest req = WebRequest.Create(uri);
   WebResponse resp = req.GetResponse();
   Stream s = resp.GetResponseStream();
   sr = new StreamReader(s);

   string t = sr.ReadToEnd();
   int i = t.IndexOf("<head>");
   int j = t.IndexOf("</head>");
   str = t.Substring(i,j);
   Console.WriteLine("{0}",str);
  }
  public static void Main()
  {

   FromBegin();
   FileS();
   SeekMethod();
   SeekSetLenth();
   ReadWrite();
   MemStream();
   BufStream();
   StringReaderWrite();
   BinReadWrite();
   WebPage();
  }
  
 }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值