用C#读写文件的方法

通常我们读取一个文件使用如下的步骤:


1、声明并使用File的OpenRead实例化一个文件流对象,就像下面这样


2、准备一个存放文件内容的字节数组,fs.Length将得到文件的实际大小,就像下面这样


3、开始读了,调用一个文件流的一个方法读取数据到data数组中


FileStream fs = File.OpenRead(filename); 或者


FileStream fs = FileStream(filename, FileMode.Open, FileAccess.Read, FileShare.Read);


byte[] data = new byte[fs.Length];


fs.Read (data, 0, data.Length);


下面的方法提供了一个比上面方法更安全的方法,来保证文件被完全读出


public static void SafeRead (Stream stream, byte[] data)
{


   int offset=0;


   int remaining = data.Length; // 只要有剩余的字节就不停的读


   while (remaining > 0)
   {
     int read = stream.Read(data, offset, remaining);


     if (read <= 0)


        throw new EndOfStreamException("文件读取到"+read.ToString()+"失败!"); // 减少剩余的字节数


        remaining -= read; // 增加偏移量


        offset += read;


    }
 }


 有些情况下你不知道流实际的长度,比如:网络流。此时可以使用类似的方法读取流直到流里面的数据完全读取出来为止。我们可以先初始化一段缓存,再将流读出来的流信息写到内存流里面,就像下面这样:


public static byte[] ReadFully (Stream stream)
{
   // 初始化一个32k的缓存


   byte[] buffer = new byte[32768];


   using (MemoryStream ms = new MemoryStream())
   {


       //返回结果后会自动回收调用该对象的Dispose方法释放内存 // 不停的读取


       while (true)
       {


            int read = stream.Read (buffer, 0, buffer.Length); // 直到读取完最后的3M数据就可以返回结果了


          if (read <= 0)


             return ms.ToArray(); ms.Write (buffer, 0, read);
        }
    }
}


虽然上面的例子都比较简单,效果也不是很明显(大部分都是对的),也许你早就会了,没关系这篇文章本来就是写给初学者的。 下面的方法提供了一种使用指定缓存长度的方式读取流,虽然在很多情况下你可以直接使用Stream.Length得到流的长度,但是不是所有的流都可以得到。


public static byte[] Read2Buffer (Stream stream, int BufferLen)
{
    // 如果指定的无效长度的缓冲区,则指定一个默认的长度作为缓存大小


    if (BufferLen < 1)
    { BufferLen = 0x8000; } // 初始化一个缓存区


    byte[] buffer = new byte[BufferLen];


    int read=0; int block; // 每次从流中读取缓存大小的数据,知道读取完所有的流为止


     while ( (block = stream.Read(buffer, read, buffer.Length-read)) > 0)
     { 


            // 重新设定读取位置


           read += block; // 检查是否到达了缓存的边界,检查是否还有可以读取的信息


           if (read == buffer.Length)
           {


              // 尝试读取一个字节


                int nextByte = stream.ReadByte(); // 读取失败则说明读取完成可以返回结果


                 if (nextByte==-1)
                 {
                     return buffer;


                 } // 调整数组大小准备继续读取


                 byte[] newBuf = new byte[buffer.Length*2]; Array.Copy(buffer, newBuf, buffer.Length);


                 newBuf[read]=(byte)nextByte; buffer = newBuf;


                 // buffer是一个引用(指针),这里意在重新设定buffer指针指向一个更大的内存


                 read++;
            }
         } // 如果缓存太大则使用ret来收缩前面while读取的buffer,然后直接返回


     byte[] ret = new byte[read]; Array.Copy(buffer, ret, read);
     return ret;
}


using System;
using System.IO;
using System.Collections;


namespace TextFileReader_csharp
{
     class Class1
     {
        static void Main(string[] args)
        {


            StreamReader objReader = new StreamReader("c:\\test.txt");


            string sLine="";


             ArrayList arrText = new ArrayList();


             while (sLine != null)
             {


                 sLine = objReader.ReadLine();


                if (sLine != null)


                 arrText.Add(sLine);


             }


             objReader.Close();


             foreach (string sOutput in arrText)
                Console.WriteLine(sOutput); Console.ReadLine();


         }
      }
}

转载于:https://www.cnblogs.com/pengwenbing/archive/2010/08/30/1812508.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值