溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

C#中的流怎么使用和分類

發(fā)布時間:2022-08-01 09:22:07 來源:億速云 閱讀:185 作者:iii 欄目:開發(fā)技術(shù)

這篇“C#中的流怎么使用和分類”文章的知識點大部分人都不太理解,所以小編給大家總結(jié)了以下內(nèi)容,內(nèi)容詳細(xì),步驟清晰,具有一定的借鑒價值,希望大家閱讀完這篇文章能有所收獲,下面我們一起來看看這篇“C#中的流怎么使用和分類”文章吧。

使用流讀取、寫入文件

使用流把文件讀取到字節(jié)數(shù)組:

//FileMode.Create, FileMode.Append 
//FileAccess.Write, FileAccess.ReadWrite 
//FileMode和FileAccess搭配使用,如果第二個參數(shù)FileMode.Appden寫追加,第三個參數(shù)FileAccess.Read只讀,會拋異常 
Stream source = new FileStream(@"1.jpg",FileMode.Open, FileAccess.Read) 
byte[] buffer = new byte[source.Length]; 
int bytesRead = source.Read(buffer, i, (int)source.Length);

Int32類型的最大值,以及Byte, KB, MB, GB轉(zhuǎn)換:

Int32.MaxValue = 2147483647 Byte 
2147483647/1024 = 2097152 KB(1 KB = 1024 Byte) 
2097152/1024 = 2048 MB(1 M = 1024 KB) 
2048/1024 = 2 G(1G = 1024M)

使用流把字節(jié)數(shù)組寫到文件:

Stream target = new FileStream(@"2.jpg", FileMode.Create, FileAccess.Write);
 
Stream source = new FileStream(@"1.jpg",FileMode.Open, FileAccess.Read) 
byte[] buffer = new byte[source.Length]; 
int bytesRead = source.Read(buffer, i, (int)source.Length);
 
target.Write(buffer, 0, buffer.Length); 
source.Dispose(); 
target.Dispose();

使用流對大文件進(jìn)行分批讀取和寫入:

int BufferSize = 10240; // 10KB 
Stream source = new FileStream(@"D:\a.mp3", FileMode.Open, FileAccess.Read); 
Stream target = new FileStream(@"D:\b.mp3", FileMode.Create, FileAccess.Write);
 
byte[] buffer = new byte[BufferSize]; 
int byteRead; 
do{ 
    byteRead = source.Read(buffer, 0, BufferSize); 
    target.Write(buffer, 0, bytesRead); 
} while(byteRead > 0); 
target.Dispose(); 
source.Dispose();

流的分類

在Stream抽象類下包含:
→FileStream→IsolatedStoreageFileStream
→MemoryStream
→NetworkStream

基礎(chǔ)流

從流中讀取數(shù)據(jù):

CanRead()
Read(byte[] buffer, int offset, int count)

向流中寫入數(shù)據(jù):

CanWrite()
Write(byte[] buffer, int offset, int count)
WriteByte(Byte value)

移動流指針:

CanSeek()
Seek(long offset, SeekOrigion)
Position流的指針位置
Close()
Dispose()
Flush()將緩存設(shè)備寫入存儲設(shè)備
CanTimeout()
ReadTimeout()
WriteTimeout()
Length
SetLength(long value)

裝飾器流

實現(xiàn)了Decorator模式,包含對Stream抽象基類的引用,同時繼承自Stream抽象基類。

  • System.IO.Compression下的DeflateStream和GZipStream用于壓縮和解壓縮

  • System.Security.Cryptography下的CryptoStream用于加密和解密

  • System.Net.Security下的AuthenticatedStream用于安全性

  • System.IO下的BufferedStream用戶緩存

包裝器類

不是流類型,而是協(xié)助開發(fā)者處理流包含的數(shù)據(jù),并且不需要將流讀取到Byte[]字節(jié)數(shù)組中。但流的包裝器類包含了對流的引用。

StreamReader

繼承自TextReader。
將流中的數(shù)據(jù)讀取為字符。

FileStream fs = new FileStream("a.txt", FileMode.Open, FileAcess.Read); 
StreamReader reader = new StreamReader(fs, Encoding.GetEncoding("GB2312"));
 
//或者 
//StreamReader reader = new StreamReader("a.txt"); //默認(rèn)采用UTF-8編碼方式
StreamWriter

繼承自TextWriter。
將字符寫入到流中。

string text = 
@"aa 
bb 
cc";
 
StringReader reader = new StringReader(text); 
int c = reader.Read(); 
Console.Write((char)c);
 
char[] buffer = new char[8]; 
reader.Read(buffer, 0, buffer.Length); 
Console.Write(String.Join("",buffer));
 
string line = reader.ReadLine(); 
Console.WriteLine(line);
 
string rest = reader.ReadToEnd(); 
Console.Write(); 
reader.Dispose();
StringReader和StringWriter

也繼承自TextReader和TextWriter,但是用來處理字符串。

BinaryWriter和BinaryReader

BinaryWriter用于向流中以二進(jìn)制方式寫入基元類型,比如int, float, char, string等.BinaryReader用于從流中讀取基元類型。注意,這2個類并不是繼承TextReader和TextWriter。

namespace ConsoleApplication29 
{ 
    class Program 
    { 
        static void Main(string[] args) 
        { 
            Product p = new Product("product.bin") 
            { 
                Id = 1, 
                Name = "GOOD", 
                Price = 500F 
            }; 
            p.Save();
 
            Product newP = new Product("product.bin"); 
            newP.Load(); 
            Console.WriteLine(newP); 
            Console.ReadKey(); 
        } 
    }
 
    public class Product 
    { 
        public int Id { get; set; } 
        public string Name { get; set; } 
        public double Price { get; set; }
 
        private string filePath;
 
        public Product(string filePath) 
        { 
            this.filePath = filePath; 
        }
 
        public void Save() 
        { 
            FileStream fs = new FileStream(this.filePath, FileMode.Create,FileAccess.Write); 
            BinaryWriter writer = new BinaryWriter(fs); 
            writer.Write(this.Id); 
            writer.Write(this.Name); 
            writer.Write(this.Price); 
            writer.Dispose(); 
        }
 
        public void Load() 
        { 
            FileStream fs = new FileStream(this.filePath, FileMode.Open,FileAccess.Read); 
            BinaryReader reader = new BinaryReader(fs); 
            this.Id = reader.ReadInt32(); 
            this.Name = reader.ReadString(); 
            this.Price = reader.ReadDouble(); 
            reader.Dispose(); 
        }
 
        public override string ToString() 
        { 
            return String.Format("Id:{0},Name:{1},Price:{2}", this.Id, this.Name, this.Price); 
        } 
    } 
}

結(jié)果:

C#中的流怎么使用和分類

編碼方式:
定義了字節(jié)如何轉(zhuǎn)換成人類可讀的字符或者文本,可以看作是字節(jié)和字符的對應(yīng)關(guān)系表。在讀取文件采用的編碼方式要和創(chuàng)建文件采用的編碼方式保持一致。

幫助類

在System.IO命名空間下。

  • File

FileStream fs = File.Create("a.txt");
Open(string path, FileMode mode)
OpenRead()
OpenWrite()
ReadAllText()
ReadAllByte()
WriteBllBytes()
WriteAllLines()
Copy(string sourceFileName, string destFileName)

  • FileInfo

  • Path

  • Directory

  • DirectoryInfo

以上就是關(guān)于“C#中的流怎么使用和分類”這篇文章的內(nèi)容,相信大家都有了一定的了解,希望小編分享的內(nèi)容對大家有幫助,若想了解更多相關(guān)的知識內(nèi)容,請關(guān)注億速云行業(yè)資訊頻道。

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI