FileStream读写文件

Namespace

using System.IO;

读文件示例

try
{
    // 打开文件
    FileStream fs = new FileStream("D:\\not.txt", FileMode.Open, FileAccess.Read);
    StreamReader sr = new StreamReader(fs);

    // 读取文件
    string strLine = sr.ReadLine();
    while (strLine != null)
    {
        Console.WriteLine(strLine);

        strLine = sr.ReadLine();
    }

    // 关闭文件
    sr.Close();
    fs.Close();
}
catch (System.IO.FileNotFoundException e)
{
    Console.WriteLine("File Not Found");
}
catch (System.Exception e)
{
    Console.WriteLine("Exception");
}

写文件示例

try
{
    FileStream fs = new FileStream("D:\\test.txt", FileMode.Create, FileAccess.Write);
    StreamWriter sw = new StreamWriter(fs);

    sw.WriteLine("aaa");
    sw.WriteLine("bbb");

    sw.Close();
    fs.Close();
}
catch (System.UnauthorizedAccessException e)
{
    Console.WriteLine("No Access To Write");
}
catch (System.Exception e)
{
    Console.WriteLine(e.ToString());
}

写入文件时经常需要去除文件的只读属性

System.IO.File.SetAttributes(strFileFullPath, System.IO.FileAttributes.Normal);

例如:

if (File.Exists("D:\\test.txt"))
{
    System.IO.File.SetAttributes("D:\\test.txt", System.IO.FileAttributes.Normal);
}

文件指针

FileStream::Seek(long offset, SeekOrigin origin);

FileMode

CreateNew
// 1.[可读][可写]
// 2.文件不存在,则创建新文件
//   文件已经存在则抛异常
// 3.可移动文件指针

Create
// 1.[可读][可写]
// 2.文件不存在,则创建新文件
//   文件已经存在,则覆盖掉
// 3.可移动文件指针

Open
// 1.[可读][可写]
// 2.文件存在则打开
//   文件不存在则抛异常
// 3.可移动文件指针

OpenOrCreate
// 1.[可读][可写]
// 2.文件存在则打开
//   文件不存在则创建
// 3.可移动文件指针

Truncate
// 1.[可写]
// 2.文件存在则打开并清空文件内存
//   文件不存在则抛异常
// 3.可移动文件指针

FileMode.Append
// 1.[可写]
// 2.文件存在则打开,并将文件指针移至文件末尾
//   文件不存在则创建
// 3.不可移动文件指针,否则会抛异常
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值