FileStream类的使用(文件流)

  • Post author:
  • Post category:其他


1、什么是FileStream类


FileStream

类对文件系统上的文件进行读取、写入、打开和关闭操作,并对其他与文件相关的操作系统句柄进行操作,如管道、标准输入和标准输出。读写操作可以指定为同步或异步操作。

FileStream

对输入输出进行缓冲,从而提高性能。——MSDN

简单点说:FileStream类可以对任意类型的文件进行读取操作,而且我们也可以根据自己需要来指定每一次读取字节长度,以此减少内存的消耗,提高读取效率。

2、File和FileStream的区别

直观点:File是一个静态类;FileStream是一个非静态类。

File:是一个

文件

的类,对文件进行操作。其内部封装了对文件的各种操作(MSDN:提供用于创建、复制、删除、移动和打开单一文件的静态方法,并协助创建FileStream对象)。

FileStream:

文件流

的类。对txt,xml,avi等文件进行内容写入、读取、复制…时候需要使用的一个工具。

打个形象的比喻。File是笔记本,需要Filestream的这个笔才能写.

换而言之,记事本是一个文件,可以用File操作,里面的内容需要用FileStream来操作。

 最常用的流类如下:
        FileStream:     文件流,可以读写二进制文件。 
        StreamReader:   流读取器,使其以一种特定的编码从字节流中读取字符。 
        StreamWriter:   流写入器,使其以一种特定的编码向流中写入字符。 
        BufferedStream: 缓冲流,给另一流上的读写操作添加一个缓冲层。
  //
        // 摘要:
        //     从流中读取字节块并将该数据写入给定缓冲区中。
        //
        // 参数:
        //   array:
        //     此方法返回时包含指定的字节数组,数组中 offset 和 (offset + count - 1) 之间的值由从当前源中读取的字节替换。
        //
        //   offset:
        //     array 中的字节偏移量,将在此处放置读取的字节。
        //
        //   count:
        //     最多读取的字节数。
        //
        // 返回结果:
        //     读入缓冲区中的总字节数。 如果字节数当前不可用,则总字节数可能小于所请求的字节数;如果已到达流结尾,则为零。
        //
        // 异常:
        //   T:System.ArgumentNullException:
        //     array 为 null。
        //
        //   T:System.ArgumentOutOfRangeException:
        //     offset 或 count 为负数。
        //
        //   T:System.NotSupportedException:
        //     流不支持读取。
        //
        //   T:System.IO.IOException:
        //     出现 I/O 错误。
        //
        //   T:System.ArgumentException:
        //     offset 和 count 描述 array 中的无效范围。
        //
        //   T:System.ObjectDisposedException:
        //     在流关闭后调用方法。
        [SecuritySafeCritical]
        public override int Read(byte[] array, int offset, int count);

          //
        // 摘要:
        //     将字节块写入文件流。
        //
        // 参数:
        //   array:
        //     包含要写入该流的数据的缓冲区。
        //
        //   offset:
        //     array 中的从零开始的字节偏移量,从此处开始将字节复制到该流。
        //
        //   count:
        //     最多写入的字节数。
        //
        // 异常:
        //   T:System.ArgumentNullException:
        //     array 为 null。
        //
        //   T:System.ArgumentException:
        //     offset 和 count 描述 array 中的无效范围。
        //
        //   T:System.ArgumentOutOfRangeException:
        //     offset 或 count 为负数。
        //
        //   T:System.IO.IOException:
        //     出现 I/O 错误。 - 或 - 另一个线程可能导致操作系统的文件句柄的位置发生意外更改。
        //
        //   T:System.ObjectDisposedException:
        //     流已关闭。
        //
        //   T:System.NotSupportedException:
        //     当前的流实例不支持写入。
        [SecuritySafeCritical]
        public override void Write(byte[] array, int offset, int count);


注:FileStream是对字节操作的(任何文件)。

//非静态类,创建对象调用方法
            using (FileStream Fsread = new FileStream(@"C:\Users\Administrator\Desktop\测试文档.txt", FileMode.OpenOrCreate, FileAccess.Read))
            {
                byte[] b = new byte[50]; 
                //用来限定每次的读取字节数,也可以byte[] b=new byte[Fsread.Length];
                string s = "";
                while (true)
                {
                    int r = Fsread.Read(b, 0, b.Length);
                    if (r == 0)
                        break;
                    s += Encoding.UTF8.GetString(b, 0, r);

                }
                Console.Write(s);
                // Fsread.Close();//关闭当前流
                // Fsread.Dispose();//释放流所使用的资源
            }

//文件流的写入
            using (FileStream fswrite = new FileStream(@"C:\Users\Administrator\Desktop\测试文档.txt", FileMode.OpenOrCreate, FileAccess.Write))
            {
                string str = "一切皆有可能";
                byte[] buffer = Encoding.UTF8.GetBytes(str);
                fswrite.Write(buffer, 0, buffer.Length);
            }

无论是读还是写,都要借助一个缓冲区buffer来存取字节。

注意:在写入和读取时,字符编码格式要相同,不然会出现乱码。

 Encoding.UTF8.GetBytes(str);
 Encoding.UTF8.GetString(b, 0, r);

//读文件

public static string ReadFile()

{

string basePath = System.AppDomain.CurrentDomain.BaseDirectory;

string strTempDir = string.Format(“{0}”, DateTime.Now.ToString(“yyyyMMdd”));

string path3 = Path.Combine(basePath, strTempDir);

FileStream fs = new FileStream(path3, FileMode.Open);

StreamReader sr = new StreamReader(fs,Encoding.UTF8);

string line = sr.ReadLine();//直接读取一行

sr.Close();

fs.Close();

return line;

}

public static string ReadFile(string sUrl)

{

StringBuilder builder = new StringBuilder();

using (FileStream fs = File.Open(sUrl, FileMode.OpenOrCreate))

{


using (StreamReader sr = new StreamReader(fs, Encoding.UTF8))

{


builder.Append(sr.ReadToEnd());

}

}

return builder.ToString();

}

//写文件

public static void WriteFile()

{

string basePath = System.AppDomain.CurrentDomain.BaseDirectory;

string strTempDir = string.Format(“{0}”, DateTime.Now.ToString(“yyyyMMdd”));

string path3 = Path.Combine(basePath, strTempDir);

FileStream fs = new FileStream(path3, FileMode.Append);

StreamWriter sw = new StreamWriter(fs);

sw.WriteLine(“hello world”);

sw.Close();

fs.Close();//这里要注意fs一定要在sw后面关闭,否则会抛异常

}

转载于:https://www.cnblogs.com/DSC1991/p/8493143.html