C#使用FileStream對象讀寫文件
在項目開發(fā)中經(jīng)常會涉及到對文件的讀寫,c# 提供了很多種方式來對文件進行讀寫操作,今天來說說FileStream 對象。
FileStream表示在磁盤或網(wǎng)絡(luò)路徑上指向文件的流。一般操作文件都習(xí)慣使用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 { //打開一個當(dāng)前 Program.cs 文件,此時讀寫文件的指針(或者說操作的光標(biāo))指向文件開頭 file = new FileStream(@"..\..\Program.cs", FileMode.Open); //讀寫指針從開頭往后移動10個字節(jié) file.Seek(10, SeekOrigin.Begin); //從當(dāng)前讀寫指針的位置往后讀取200個字節(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)建一個編碼轉(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)前啟動目錄下的創(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)建一個編碼器,將字符轉(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)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
C#更新SQLServer中TimeStamp字段(時間戳)的方法
這篇文章主要介紹了C#更新SQLServer中TimeStamp字段(時間戳)的方法,涉及C#操作數(shù)據(jù)庫字段的相關(guān)技巧,需要的朋友可以參考下2015-05-05C#實現(xiàn)在前端網(wǎng)頁彈出警告對話框(alert)的方法
這篇文章主要介紹了C#實現(xiàn)在前端網(wǎng)頁彈出警告對話框(alert)的方法,涉及C#通過自定義函數(shù)調(diào)用window.alert方法彈出對話框的技巧,具有一定參考借鑒價值,需要的朋友可以參考下2015-04-04.net 通過 WebAPI 調(diào)用nsfwjs 進行視頻鑒別功能
這篇文章主要介紹了.net 通過 WebAPI 調(diào)用 nsfwjs 進行視頻鑒別,文末給大家提到了FFMPEG獲取視頻關(guān)鍵幀并保存成jpg圖像的相關(guān)知識,需要的朋友可以參考下2021-09-09C#中的modbus Tcp協(xié)議的數(shù)據(jù)抓取和使用解析
這篇文章主要介紹了C#中的modbus Tcp協(xié)議的數(shù)據(jù)抓取和使用解析,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-07-07