当前位置:编程学习 > C#/ASP.NET >>

用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
补充:软件开发 , C# ,
CopyRight © 2012 站长网 编程知识问答 www.zzzyk.com All Rights Reserved
部份技术文章来自网络,