FileStream
以下演示與FileStream配合的資料寫入讀出的範例
一、使用FileStream做創立、寫入設定,並藉由StreamWriter.Write()寫入資料
FileStream filestream = new FileStream(@"d:\stream.txt", FileMode.Create, FileAccess.Write);
string sStringText = "sStringText2";
StreamWriter sw = new StreamWriter(filestream, Encoding.Default);
sw.Write(sStringText);
sw.Close();
filestream.Close();
二、使用FileStream做開啟、讀取設定,並藉由StreamReader.ReadToEnd()讀取資料
filestream = new FileStream(@"d:\stream.txt", FileMode.Open, FileAccess.Read);
StreamReader sr = new StreamReader(filestream, Encoding.Default);
Console.WriteLine(sr.ReadToEnd());
sr.Close();
三、使用FileStream.Write方法將資料寫入檔案(buffer to FileStream instance)
using System;
using System.Text;
using System.IO;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
try
{
//使用FileStream將資料寫入檔案
FileStream filestream = new FileStream(@"d:\stream.txt", FileMode.Create, FileAccess.Write);
string sStringText = "sStringText";
char[] cCharArray = null;
cCharArray = sStringText.ToCharArray();
byte[] bBytes = new byte[cCharArray.Length];
for (int i = 0; i <= cCharArray.Length - 1; i++)
{
bBytes[i] = Convert.ToByte(cCharArray[i]);
}
filestream.Write(bBytes, 0, bBytes.Length);
filestream.Close();
Console.WriteLine("finish");
Console.ReadKey();
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
Console.ReadKey();
}
}
}
}
由以上程式可知將字串寫入檔案的方式,是使用FileStream.Write,
是將待寫入的字串先轉成char陣列,然後再轉成byte陣列,
最後利用FileStresm.Write()方法,把byte陣列寫入檔案裡,
開啟檔案就會發現字串sStringText已經寫在裡面了。
值得注意的是,從watch來看,char陣列與byte陣列裡的數值皆為十進位表示,
十進位是轉給開發人員看的,並不表示char與byte就是十進制。
四、FileStream.Write方法與Stream.Read方法的配合應用
using System;
using System.IO;
using System.Net;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
try
{
WebRequest request = WebRequest.Create("HTTP://images.cnblogs.com/logo_small.gif");
WebResponse response = request.GetResponse();
Stream reader = response.GetResponseStream();
FileStream writer = new FileStream(@"d:\pic.jpg", FileMode.OpenOrCreate, FileAccess.Write);
byte[] buff = new byte[512];
int c = 0;
while ((c = reader.Read(buff, 0, buff.Length)) > 0)
{
writer.Write(buff, 0, c);
}
writer.Close();
writer.Dispose();
reader.Close();
reader.Dispose();
response.Close();
Console.WriteLine("finish");
Console.ReadKey();
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
Console.ReadKey();
}
}
}
}
說明:
此範例功能為從網路下載圖片,從網路的stream轉存成檔案的filestream,
此程式主要分為兩部分,一為從網路存資料到緩衝區,第二部分為從緩衝區將資料存成檔案。
一開始為從網路response個stream回來,
然後使用Stream.Read(buff,offset,count)語法為從Stream讀取資料到buff陣列(緩衝區)裡面,
如果程式為每讀一次寫一次則偏移位置可以為零,代表每次都可以覆寫緩衝區,
如為整批讀完整批寫入的話,則每一次的讀取後都需要使用偏移值來指定預寫指標,以防在緩衝區的資料被覆寫到,
每次讀取量通常是由陣列buff.Length指定,讀取量可以小於緩衝區,批次讀取直到讀取完畢,
通常緩衝區會指定的比較小所以無法一次讀完,Stream.Read方法會回傳此次讀取量,
如果已到資料末端時會回傳長度為零。
第二部分從緩衝區資料轉存成檔案,用法與Stream.Read類似,請參考第一範例。
五、FileStream.Write方法與StreamReader.Read方法的配合應用
using System;
using System.IO;
using System.Net;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
string result = "";
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("https://dotblogs.com.tw/brooke");
request.Method = WebRequestMethods.Http.Get;
try
{
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
if (response.StatusCode == HttpStatusCode.OK)
{
Stream stream = response.GetResponseStream();
StreamReader streamReader = new StreamReader(stream);
char[] buffer = new char[512];//buffer大小可自由設定,通常不會設太大
int data = 0;
while ((data = streamReader.Read(buffer, 0, buffer.Length)) > 0)
{
string msg = new string(buffer, 0, data);
result = result + msg;
}
if (streamReader != null) streamReader.Close();
if (stream != null) stream.Close();
}
if (response != null) response.Close();
}
catch (WebException ex1)
{
HttpWebResponse exResponse = (HttpWebResponse)ex1.Response;
Console.WriteLine(ex1.Message);
}
catch (NotSupportedException ex2)
{
Console.WriteLine(ex2.Message);
}
catch (ProtocolViolationException ex3)
{
Console.WriteLine(ex3.Message);
}
catch (InvalidOperationException ex4)
{
Console.WriteLine(ex4.Message);
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
finally
{
}
}
}
}
六、FileStream.Read方法寫到buffer(FileStream instance to buffer)
using System;
using System.IO;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
FileStream fs = new FileStream(Directory.GetCurrentDirectory() + @"\pic.png", FileMode.Open);
int length = (int)fs.Length;
byte[] buffer = new byte[length];
int count;
int sum = 0;
//fs資料寫到buffer
//回傳buffer已讀取的總位元組數 FileStream.Read(buffer, buffer的索引「從零開始寫」, 準備要寫入buffer的最大位元組數)
while ((count = fs.Read(buffer, sum, length - sum)) > 0)
sum += count;
fs.Close();
Console.ReadLine();
}
}
}
七、以下為VB.NET範例僅供參考
Imports System.IO Imports System.Text '參考網址:http://www.dotblogs.com.tw/yc421206/archive/2009/01/18/6862.aspx Module Module1 Sub Main() Try '***先建立範例檔*** If Directory.Exists("c:/system_io_test") = False Then Directory.CreateDirectory("c:/system_io_test") '建立資料夾與檔案 File.Create("c:/system_io_test/aaa.txt").Dispose() File.Create("c:/system_io_test/aaa2.txt").Dispose() File.Create("c:/system_io_test/aaa3.txt2").Dispose() End If If Directory.Exists("c:/system_io_test/inDir") = False Then Directory.CreateDirectory("c:/system_io_test/inDir") File.Create("c:/system_io_test/inDir/aaa4.txt").Dispose() End If File.WriteAllText("c:/system_io_test/aaa.txt", "content1") '將字串content1寫進路徑txt中 File.WriteAllText("c:/system_io_test/aaa2.txt", "content2") '將字串content2寫進路徑txt中 File.WriteAllText("c:/system_io_test/aaa3.txt2", "content3") '將字串content3寫進路徑txt中 File.WriteAllText("c:/system_io_test/inDir/aaa4.txt", "content4") '將字串content4寫進路徑txt中 '1.Directory列舉目錄與子目錄的方法 Dim filepaths() As String = Directory.GetFiles("c:\system_io_test\") '列舉出aaa aaa2 aaa3路徑 Dim bmpFilePaths() As String = Directory.GetFiles("c:\system_io_test", "*.txt2") '列舉出aaa3路徑 Dim allFilePath() As String = Directory.GetFiles("c:\system_io_test", "*.txt", SearchOption.AllDirectories) '列舉出aaa aaa2 aaa3 aaa4路徑 '2.File提供檔案建立、複製、移動的靜態方法,並協助建立StreamWriter Dim sw As StreamWriter = File.CreateText("c:\system_io_test\CreateText1.txt") sw.Write("CreateText1") sw.Close() File.WriteAllText("c:/system_io_test/aaa.txt", "WriteAllText1") '將字串WriteAllText寫進路徑aaa.txt中 Dim fileDate As Date = File.GetCreationTime("c:/system_io_test/aaa.txt") '針對aaa.txt檔取得創立時間 '2.1使用File讀整個檔案,每行塞入字串陣列 Dim sStrings() As String = File.ReadAllLines("c:/system_io_test/aaa.txt") '3.1FileStream資料寫入檔案 Dim filestream As New FileStream("c:/system_io_test/stream.txt", FileMode.Create, FileAccess.Write) Dim sStringText As String = "sStringText" Dim cCharText() As Char cCharText = sStringText.ToCharArray Dim bBytes() As Byte = New Byte(cCharText.Length - 1) {} For i = 0 To cCharText.Length - 1 bBytes(i) = CByte(AscW(cCharText(i))) Next filestream.Write(bBytes, 0, bBytes.Length) filestream.Close() '3.1.1 FileStream資料寫入檔案配合StreamWrite filestream = New FileStream("c:/system_io_test/stream.txt", FileMode.Create, FileAccess.Write) sStringText = "3.1.1FileStream資料寫入檔案配合StreamWrite" sw = New StreamWriter(filestream, Encoding.Default) sw.Write(sStringText) sw.Close() filestream.Close() '3.2FileStream資料讀出 filestream = New FileStream("c:/system_io_test/stream.txt", FileMode.Open, FileAccess.Read) Dim sr As New StreamReader(filestream, Encoding.Default) 'Dim sr As New StreamReader(filestream) '第二種寫法 MsgBox(sr.ReadToEnd()) sr.Close() '4.FileInfo用來幫助File精簡程式 Dim FileInfo As New FileInfo("c:/system_io_test/info2.txt") Dim swOpFileInfo As StreamWriter = FileInfo.CreateText swOpFileInfo.WriteLine("test") swOpFileInfo.Close() MsgBox("完成") Catch ex As Exception MsgBox(ex.ToString) End Try End Sub End Module
參考資料: