FileStream读写文件

读文件示例

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.不可移动文件指针,否则会抛异常
原文地址:https://www.cnblogs.com/as3lib/p/6415753.html