C#使用FileStream對象讀寫文件
在項目開發(fā)中經(jīng)常會涉及到對文件的讀寫,c# 提供了很多種方式來對文件進行讀寫操作,今天來說說FileStream 對象。
FileStream表示在磁盤或網(wǎng)絡路徑上指向文件的流。一般操作文件都習慣使用StreamReader 和 StreamWriter,因為它們操作的是字符數(shù)據(jù) 。而FileStream 對象操作的是字節(jié)和字節(jié)數(shù)組。有些操作是必須使用FileStream 對象執(zhí)行的,如隨機訪問文件中間某點的數(shù)據(jù)。
創(chuàng)建FileStream 對象有許多不同的方法,這里使用文件名和FileMode枚舉值創(chuàng)建:
一、 讀取文件,記得引用 System.IO 命名空間:
using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
namespace ConsoleApplicationTest
{
class Program
{
static void Main(string[] args)
{
//創(chuàng)建需要讀取的數(shù)據(jù)的字節(jié)數(shù)組和字符數(shù)組
byte[] byteData = new byte[200];
char[] charData = new char[200];
//捕獲異常:操作文件時容易出現(xiàn)異常,最好加上try catch
FileStream file = null;
try
{
//打開一個當前 Program.cs 文件,此時讀寫文件的指針(或者說操作的光標)指向文件開頭
file = new FileStream(@"..\..\Program.cs", FileMode.Open);
//讀寫指針從開頭往后移動10個字節(jié)
file.Seek(10, SeekOrigin.Begin);
//從當前讀寫指針的位置往后讀取200個字節(jié)的數(shù)據(jù)到字節(jié)數(shù)組中
file.Read(byteData, 0, 200);
}catch(Exception e)
{
Console.WriteLine("讀取文件異常:{0}",e);
}
finally
{
//關閉文件流
if(file !=null) file.Close();
}
//創(chuàng)建一個編碼轉換器 解碼器
Decoder decoder = Encoding.UTF8.GetDecoder();
//將字節(jié)數(shù)組轉換為字符數(shù)組
decoder.GetChars(byteData, 0, 200, charData, 0);
Console.WriteLine(charData);
Console.ReadKey();
}
}
}
顯示結果如下:

二、寫入文件:
using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
namespace ConsoleApplicationTest
{
class Program
{
static void Main(string[] args)
{
byte[] byteData;
char[] charData;
FileStream file = null;
try
{
//在當前啟動目錄下的創(chuàng)建 aa.txt 文件
file = new FileStream("aa.txt", FileMode.Create);
//將“test write text to file”轉換為字符數(shù)組并放入到 charData 中
charData = "Test write text to file".ToCharArray();
byteData = new byte[charData.Length];
//創(chuàng)建一個編碼器,將字符轉換為字節(jié)
Encoder encoder = Encoding.UTF8.GetEncoder();
encoder.GetBytes(charData, 0, charData.Length, byteData, 0,true);
file.Seek(0, SeekOrigin.Begin);
//寫入數(shù)據(jù)到文件中
file.Write(byteData, 0, byteData.Length);
}catch(Exception e)
{
Console.WriteLine("寫入文件異常:{0}",e);
}
finally
{
if (file != null) file.Close();
}
Console.ReadKey();
}
}
}
結果如下:

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
相關文章
c#讀寫App.config,ConfigurationManager.AppSettings 不生效的解決方法
這篇文章主要介紹了c#讀寫App.config,ConfigurationManager.AppSettings 不生效的解決方法,需要的朋友可以參考下2015-10-10

