C#使用FileStream對(duì)象讀寫文件
在項(xiàng)目開發(fā)中經(jīng)常會(huì)涉及到對(duì)文件的讀寫,c# 提供了很多種方式來對(duì)文件進(jìn)行讀寫操作,今天來說說FileStream 對(duì)象。
FileStream表示在磁盤或網(wǎng)絡(luò)路徑上指向文件的流。一般操作文件都習(xí)慣使用StreamReader 和 StreamWriter,因?yàn)樗鼈儾僮鞯氖亲址麛?shù)據(jù) 。而FileStream 對(duì)象操作的是字節(jié)和字節(jié)數(shù)組。有些操作是必須使用FileStream 對(duì)象執(zhí)行的,如隨機(jī)訪問文件中間某點(diǎn)的數(shù)據(jù)。
創(chuàng)建FileStream 對(duì)象有許多不同的方法,這里使用文件名和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];
//捕獲異常:操作文件時(shí)容易出現(xiàn)異常,最好加上try catch
FileStream file = null;
try
{
//打開一個(gè)當(dāng)前 Program.cs 文件,此時(shí)讀寫文件的指針(或者說操作的光標(biāo))指向文件開頭
file = new FileStream(@"..\..\Program.cs", FileMode.Open);
//讀寫指針從開頭往后移動(dòng)10個(gè)字節(jié)
file.Seek(10, SeekOrigin.Begin);
//從當(dāng)前讀寫指針的位置往后讀取200個(gè)字節(jié)的數(shù)據(jù)到字節(jié)數(shù)組中
file.Read(byteData, 0, 200);
}catch(Exception e)
{
Console.WriteLine("讀取文件異常:{0}",e);
}
finally
{
//關(guān)閉文件流
if(file !=null) file.Close();
}
//創(chuàng)建一個(gè)編碼轉(zhuǎn)換器 解碼器
Decoder decoder = Encoding.UTF8.GetDecoder();
//將字節(jié)數(shù)組轉(zhuǎn)換為字符數(shù)組
decoder.GetChars(byteData, 0, 200, charData, 0);
Console.WriteLine(charData);
Console.ReadKey();
}
}
}
顯示結(jié)果如下:

二、寫入文件:
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
{
//在當(dāng)前啟動(dòng)目錄下的創(chuàng)建 aa.txt 文件
file = new FileStream("aa.txt", FileMode.Create);
//將“test write text to file”轉(zhuǎn)換為字符數(shù)組并放入到 charData 中
charData = "Test write text to file".ToCharArray();
byteData = new byte[charData.Length];
//創(chuàng)建一個(gè)編碼器,將字符轉(zhuǎn)換為字節(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();
}
}
}
結(jié)果如下:

以上就是本文的全部內(nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
C#中事務(wù)處理和非事務(wù)處理方法實(shí)例分析
這篇文章主要介紹了C#中事務(wù)處理和非事務(wù)處理方法,較為詳細(xì)的分析了C#中事務(wù)處理與非事務(wù)處理的使用技巧,對(duì)于使用C#進(jìn)行數(shù)據(jù)庫程序開發(fā)有一定參考借鑒價(jià)值,需要的朋友可以參考下2015-07-07
c#讀寫App.config,ConfigurationManager.AppSettings 不生效的解決方法
這篇文章主要介紹了c#讀寫App.config,ConfigurationManager.AppSettings 不生效的解決方法,需要的朋友可以參考下2015-10-10
C#調(diào)用OpenCV開發(fā)簡易版美圖工具【推薦】
本文主要介紹在WPF項(xiàng)目中使用OpenCVSharp3-AnyCPU開源類庫處理圖片,本文通過實(shí)例代碼給大家介紹的非常詳細(xì),具有一定的參考借鑒價(jià)值,需要的朋友參考下吧2019-10-10

