FileStream对象表示在磁盘或网络路径上指向文件的流。这个类提供了在文件中读写字节的方法,但经常使用StreamReader或StreamWriter执行这些功能。这是因为FileStream类操作的是字节和字节数组,而Stream类操作的是字符数据。字符数据易于使用,但是有些操作,比如随机文件访问(访问文件中间某点的数据),就必须由FileStream对象执行.
其中创建FileStream对象最简单的构造函数如下:

1        FileStream file = new FileStream(fileName,FileMode.Member);
2        FileStream file = new FileStream(fileName, FileMode.Member, FileAccess.Member);
而FileAccess的成员:

成 员

说 明

Read

打开文件,用于只读

Write

打开文件,用于只写

ReadWrite

打开文件,用于读写

对文件进行不是FileAccess枚举成员指定的操作会导致抛出异常。此属性的作用是,基于用户的身份验证级别改变用户对文件的访问权限。

在FileStream构造函数不使用FileAccess枚举参数的版本中,使用默认值FileAccess. ReadWrite。

FileMode枚举成员,使用每个值会发生什么,取决于指定的文件名是否表示已有的文件。

成 员

文 件 存 在

文件不存在

Append

打开文件,流指向文件的末尾,只能与枚举FileAccess.Write联合使用

创建一个新文件。只能与枚举FileAccess.Write联合使用

Create

删除该文件,然后创建新文件

创建新文件

CreateNew

抛出异常

创建新文件

Open

打开现有的文件,流指向文件的开头

抛出异常

OpenOrCreate

打开文件,流指向文件的开头

创建新文件

Truncate

打开现有文件,清除其内容。流指向文件的开头,保留文件的初始创建日期

抛出异常

 

FileStream类操作的是字节和字节数组,而Stream类操作的是字符数据
StreamWriter允许将字符和字符串写入文件,它处理底层的转换,向FileStream对象写入数据。StreamReader也类似。

实例:

  1using System;
  2using System.Data;
  3using System.IO;
  4using System.Text;
  5
  6/// <summary>
  7/// Summary description for FileReadAndWrite
  8/// </summary>
  9public class FileReadAndWrite
 10{
 11    public FileReadAndWrite()
 12    {
 13        //
 14        // TODO: Add constructor logic here
 15        //
 16    }
 17    /// <summary>
 18    /// 用FileStream写文件
 19    /// </summary>
 20    /// <param name="str"></param>
 21    /// <returns></returns>
 22    public void FileStreamWriteFile(string str)
 23    {
 24        byte[] byData;
 25        char[] charData;
 26        try
 27        {
 28            FileStream nFile = new FileStream("love.txt", FileMode.Create);
 29            //获得字符数组
 30            charData = str.ToCharArray();
 31            //初始化字节数组
 32            byData = new byte[charData.Length];
 33            //将字符数组转换为正确的字节格式
 34            Encoder enc = Encoding.UTF8.GetEncoder();
 35            enc.GetBytes(charData, 0, charData.Length,byData,0,true);
 36            nFile.Seek(0, SeekOrigin.Begin);
 37            nFile.Write(byData, 0, byData.Length);
 38        }
 39        catch (Exception ex)
 40        {
 41            throw ex;
 42        }
 43    }
 44    /// <summary>
 45    /// FileStream读取文件
 46    /// </summary>
 47    /// <param name="filePath"></param>
 48    /// <returns></returns>
 49    public string FileStreamReadFile(string filePath)
 50    {
 51        byte[] data = new byte[100];
 52        char[] charData = new char[100];
 53        try
 54        {
 55            FileStream file = new FileStream(filePath, FileMode.Open);
 56            //文件指针指向0位置
 57            file.Seek(0, SeekOrigin.Begin);
 58            //读入两百个字节
 59            file.Read(data, 0, 200);
 60            //提取字节数组
 61            Decoder dec = Encoding.UTF8.GetDecoder();
 62            dec.GetChars(data, 0, data.Length, charData, 0);
 63        }
 64        catch (Exception ex)
 65        {
 66            throw ex;
 67        }
 68        return Convert.ToString(charData);
 69    }
 70    /// <summary>
 71    /// StreamWriter写文件
 72    /// </summary>
 73    public void StreamWriterWriteFile()
 74    {
 75        try
 76        {
 77            FileStream nFile = new FileStream("love.txt", FileMode.CreateNew);
 78            StreamWriter writer = new StreamWriter(nFile);
 79
 80            writer.WriteLine("I love You!");
 81            writer.WriteLine("Do you love me!");
 82            writer.Close();
 83        }
 84        catch
 85        { }
 86    }
 87    /// <summary>
 88    /// StreamReader读取文件
 89    /// </summary>
 90    /// <returns></returns>
 91    public string StreamReaderReadFile()
 92    {
 93        string str="";
 94        try
 95        {
 96            FileStream file = new FileStream("love.txt", FileMode.Open);
 97            StreamReader sr = new StreamReader(file);
 98            while (sr.ReadLine()!=null)
 99            {
100                str += sr.ReadLine();
101            }
102            //或者str = sr.ReadToEnd();
103            sr.Close();
104        }
105        catch
106        { }
107        return str;
108    }
109}
110

FileStream读写文件【StreamWriter 和 StreamReader】的更多相关文章

  1. [转载]FileStream读写文件

    FileStream读写文件 FileStream类:操作字节的,可以操作任何的文件 StreamReader类和StreamWriter类:操作字符的,只能操作文本文件. 1.FileStream类 ...

  2. FileStream读写文件流

    用FileStream 读取文件流并显示给文件内容 string p = @"C:\Users\Administrator\Desktop\1.txt"; FileStream f ...

  3. FileStream读写文件

    读文件示例 try { // 打开文件 FileStream fs = new FileStream("D:\\not.txt", FileMode.Open, FileAcces ...

  4. C#读写文件总结

    1.使用FileStream读写文件   文件头:   using System; using System.Collections.Generic; using System.Text; using ...

  5. C# 之 读写文件

    1.使用 FileStream 读写文件 添加命名空间引用: using System; using System.Collections.Generic; using System.Text; us ...

  6. C#文件与流(FileStream、StreamWriter 、StreamReader 、File、FileInfo、Directory、directoryInfo、Path、Encoding)

    (FileStream.StreamWriter .StreamReader .File.FileInfo.Directory.DirectoryInfo.Path.Encoding)     C#文 ...

  7. (整理)streamWriter、streamReader与FileStream

    今天偶然使用VS代码分析,发现CA2000警告,然后其中一条为streamWriter.streamReader与FileStream相关内容,特查询并记录一下. 引文地址:http://bbs.cs ...

  8. C#常用IO流与读写文件

    .文件系统 ()文件系统类的介绍 文件操作类大都在System.IO命名空间里.FileSystemInfo类是任何文件系统类的基类:FileInfo与File表示文件系统中的文件:Directory ...

  9. C#常用IO流与读写文件 (转)

    源自https://www.cnblogs.com/liyangLife/p/4797583.html 谢谢 1.文件系统 (1)文件系统类的介绍 文件操作类大都在System.IO命名空间里.Fil ...

随机推荐

  1. Linux磁盘分区及配额123

    实验目的: 在现有磁盘的基础上进行分区格式化并为特定用户实施磁盘配额,使其对磁盘这一分区的写入有一定的限制 前期准备: 在我的虚拟机rhel7上有/dev/sda这一分区和fsy这一用户,我将对/de ...

  2. datagrid

    <!DOCTYPE html><html><head> <style>body {  font-family: Helvetica Neue, Aria ...

  3. 练习用基础SQL语句

    http://www.cnblogs.com/zxlovenet/p/3728842.html 本文语句大部分SQL语句来自<数据库系统概论>(第四版)王珊&萨师煊 ,是我们上课用 ...

  4. 安装LNMP(Nginx+Mysql+PHP)

    1:安装nginxyum install -y gcc pcre-devel openssl-develwget http://www.nginx.org/download/nginx-1.4.2.t ...

  5. Linux 命令

    Linux 常用命令 su root  切换root用户 touch /etc/www/html/1.txt  创建文件 mkdir /usr/local/apache2   建立文件夹 rm -rf ...

  6. nginx+Memcached 缓存设计

    单页面缓存方案 单静态页缓存 解决问题场景 常见的缓存设计利用System.Web.Cache 保存在内存内,效率高,可以减轻数据库访问的压力.但是Web除了获取数据之外,还有呈现页面渲染,生成HTM ...

  7. Excel——MATCH函数

    使用 MATCH 函数在范围单元格中搜索特定的项,然后返回该项在此区域中的相对位置. 1.参数说明: MATCH(lookup_value, lookup_array, [match_type]) l ...

  8. postgresql中的CUBE函数

    数据函数简介添加汇总额外信息 数据 --复杂统计函数 CREATE TABLE t3 (color_type varchar(20), in_date varchar(30),color_count ...

  9. 解决 release-stripped.ap_' specified for property 'resourceFile' does not exist.

    设置buildTypes里的release的shrinkResources为false即可,如果是 release-stripped.ap_' specified for property 'reso ...

  10. How to see the "real" available resources ?

    Hi, Hope this will help you : nova hypervisor-stats It will return the statistics of the Hypervisor ...