C#的位元組與流

来源:https://www.cnblogs.com/supersnowyao/archive/2018/01/22/8327727.html
-Advertisement-
Play Games

電腦中文件有很多種,我們知道實際存在電腦中的都是二進位。這裡我記錄了通過流對文件的讀取操作。 一、首先在這裡簡單涉及下位,位元組,字元的概念。 位(bit):可以表示0或1; 位元組(byte):由8位組成(bit),可以表示0-255,是256個不同的數據; 字元:字元根據編碼的不同有所區別; A ...


     電腦中文件有很多種,我們知道實際存在電腦中的都是二進位。這裡我記錄了通過流對文件的讀取操作。

     一、首先在這裡簡單涉及下位,位元組,字元的概念。

     位(bit):可以表示0或1;

     位元組(byte):由8位組成(bit),可以表示0-255,是256個不同的數據;

     字元:字元根據編碼的不同有所區別;

     ANSI編碼(本地化):它是支持本地的編碼方式,不同 ANSI 編碼之間互不相容。在簡體中文系統下,ANSI 編碼代表 GB2312 編碼,在日文操作系統下,ANSI 編碼代表 JIS 編碼。對於字元來說ANSI以單位元組存放英文字元,以雙位元組存放中文等字元。

     Unicoide編碼:Unicode下,英文和中文的字元都以雙位元組存放。用來給 UNICODE 字元集編碼的標準有很多種,比如:UTF-8, UTF-7, UTF-16, UnicodeLittle, UnicodeBig 等。

     UTF-8:是表示一個字元是可變的,有可能是用一個位元組表示一個字元,也可能是兩個,三個。當然最多不能超過3個位元組了。反正是根據字元對應的數字大小來確定。

     UTF-16:任何字元對應的數字都用兩個位元組來保存。

 

     二、C# Stream流的主要用途就是與應用程式外部的文件或者數據源進行數據交互。

     有文件流FileStream,網路流NetwrokStream,訪問網路時InputStream,OutputStream等。流的內部就是對二進位數據的讀取。

     流可以一次性讀取,也可以迴圈讀取。

     一次性讀取:

 1 public void Read()  
 2 {  
 3     string filePath = Environment.CurrentDirectory + "/content.txt";  
 4     Stream source = new FileStream(filePath, FileMode.Open, FileAccess.Read);  
 5 
 6     byte[] buffer = new byte[source.Length];  
 7     int bytesRead = source.Read(buffer, 0, (int)source.Length);  
 8 
 9     Output(buffer);      
10 } 

     迴圈讀取:

 public void ReadLoop()  
 2 {  
 3     string filePath = Environment.CurrentDirectory + "/content.txt";  
 4     string fileDest = Environment.CurrentDirectory + "/dest.txt";  
 5     Stream source = new FileStream(filePath, FileMode.Open, FileAccess.Read);  
 6     Stream destStream = new FileStream(fileDest, FileMode.Create, FileAccess.Write);  
 7 
 8     int bufferSize = 10;  
 9     byte[] buffer = new byte[bufferSize];  
10     int bytesREad;  
11     while((bytesREad= source.Read(buffer, 0, bufferSize)>0))
        {
            destStream.Write(buffer, 0, bytesREad);
        }
18     source.Dispose();  
19     destStream.Dispose();  
20 } 

     StreamReader, StreamWriter。StringReader, StringWriter。它們是流的包裝器類,方便對流的讀取。以下是示例代碼:

1 public void StreamReaderRead()  
2 {  
3     string filePath = Environment.CurrentDirectory + "/content.txt";  
4     Stream source = new FileStream(filePath, FileMode.Open, FileAccess.Read);  
5     StreamReader sr = new StreamReader(source);//Stream包裝器類  
6     string text = sr.ReadToEnd();  
7 
8     Console.Write(text);  
9 } 
 1 public void StreamWriterWrite()  
 2 {  
 3     string filePath = Environment.CurrentDirectory + "/content.txt";  
 4     string fileDest = Environment.CurrentDirectory + "/dest1.txt";  
 5       
 6     Stream source = new FileStream(filePath, FileMode.Open, FileAccess.Read);  
 7 
 8     StreamReader sr = new StreamReader(source);//Stream包裝器類  
 9     string text = sr.ReadToEnd();  
10 
11     StreamWriter sw = new StreamWriter(fileDest);//Stream包裝器類  
12     sw.Write(text);  
13     sw.Flush();  
14     sw.Close();  
15 } 

 

     三、二進位位元組流讀寫封裝

     完成以下功能:

  • 只針對記憶體位元組流的讀寫,主要應用於數據的解析和寫入。
  • 提供不同數據類型的讀寫介面,包括byte,short,int,float,string等。
  • 處理了大小端數據轉換的問題,所以可用於網路數據的解析和發送。
  1 using System.IO; 
  2 using System.Net;
  3 using System;
  4 
  5 namespace Framework
  6 {
  7     public class NetStream
  8     {
  9         private MemoryStream stream;
 10         private BinaryReader reader;
 11         private BinaryWriter writer;
 12 
 13         public NetStream(byte[] buffer = null)
 14         {
 15             if (buffer == null)
 16             {
 17                 this.stream = new MemoryStream();
 18             }
 19             else
 20             {
 21                 this.stream = new MemoryStream(buffer);
 22             }
 23 
 24             this.reader = new BinaryReader(this.stream);
 25             this.writer = new BinaryWriter(this.stream);
 26         }
 27 
 28         public void Close()
 29         {
 30             this.stream.Close();
 31             this.reader.Close();
 32             this.writer.Close();
 33         }
 34 
 35 //-------------------------------------------------------------------------------
 36 
 37         public long ReadInt64()
 38         {
 39             return IPAddress.HostToNetworkOrder(this.reader.ReadInt64());
 40         }
 41 
 42         public int ReadInt32() 
 43         {
 44             return IPAddress.HostToNetworkOrder(this.reader.ReadInt32());
 45         }
 46 
 47         public short ReadInt16() 
 48         {
 49             return IPAddress.HostToNetworkOrder(this.reader.ReadInt16());
 50         }
 51 
 52         public byte ReadByte()
 53         {
 54             return this.reader.ReadByte();
 55         }
 56 
 57         public float ReadFloat()
 58         {
 59             return this.reader.ReadSingle();
 60         }
 61 
 62         public string ReadString8() 
 63         {
 64             return System.Text.Encoding.UTF8.GetString(this.reader.ReadBytes(ReadByte()));
 65         }
 66 
 67         public string ReadString16() 
 68         {
 69             return System.Text.Encoding.UTF8.GetString(this.reader.ReadBytes(ReadInt16()));
 70         }
 71 
 72         public long Seek(long offset)
 73         {
 74             return this.stream.Seek(offset, SeekOrigin.Begin);
 75         }
 76 
 77 //-------------------------------------------------------------------------------
 78 
 79         public void WriteByte(byte value)
 80         {
 81             this.writer.Write(value);
 82         } 
 83 
 84         public void WriteInt16(short value)
 85         {
 86             this.writer.Write(BitConverter.GetBytes(IPAddress.HostToNetworkOrder(value)));
 87         }
 88 
 89         public void WriteInt32(int value)
 90         {
 91             this.writer.Write(BitConverter.GetBytes(IPAddress.HostToNetworkOrder(value)));
 92         }
 93 
 94         public void WriteInt64(long value)
 95         {
 96             this.writer.Write(BitConverter.GetBytes(IPAddress.HostToNetworkOrder(value)));
 97         }
 98 
 99         public void WriteFloat(float value)
100         {
101             this.writer.Write(value);
102         }
103 
104         public void WriteString8(string value)
105         {
106             byte[] byteArray = System.Text.Encoding.UTF8.GetBytes(value);
107 
108             WriteByte((byte) byteArray.Length);
109 
110             this.writer.Write(byteArray);
111         }
112 
113         public void WriteString16(string value)
114         {
115             byte[] byteArray = System.Text.Encoding.UTF8.GetBytes(value);
116 
117             WriteInt16((short) byteArray.Length);
118 
119             this.writer.Write(byteArray);
120         }
121 
122         public byte[] GetBuffer()
123         {
124             return this.stream.ToArray();
125         }
126 
127         public int GetLength()
128         {
129             return (int) this.stream.Length;
130         }
131     }
132 }

 

轉載鏈接:http://blog.csdn.net/qq_26054303/article/details/53019064

       http://blog.csdn.net/tom_221x/article/details/72330107


您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
  • 使用 報錯:Sys.WebForms.PageRequestManagerParserErrorException:無法分析從伺服器收到的消息 使用 依舊報錯:Sys.WebForms.PageRequestManagerParserErrorException:無法分析從伺服器收到的消息 後,嘗試 ...
  • 在顯示層用如下代碼,把需要存儲的值放到線程擁有者里,代碼如下 在Service層調用的時候如下: 請問這樣把Seesion共用到Service可行嗎? ...
  • 需要添加引用 Microsoft.Office.Interop.Excel 有興趣的可以看看 https://www.cnblogs.com/junshijie/p/5292087.html 這篇文章,裡面有更詳細如何操作EXCEL。 ...
  • 最近在自覺python,看到了知乎上一篇文章(https://www.zhihu.com/question/20799742),在福利網上爬視頻。。。 由是我就開始跟著做了,但答主給的例子是基於python2.x的,而我開始學的是3.x,把print用法改了以後還是有很多模塊導入不了,新手又不知道該 ...
  • 第一步: 在命令行中輸入 C:\Program Files (x86)\Microsoft Visual Studio 12.0\Common7\IDE 第二步: 根據用戶查找該用戶下workspace(工作空間): 輸入: tf workspaces /owner:[Account] /serve ...
  • #region 測試EPPlus插入圖片 public static void Createsheel2() { WebClient client = new WebClient(); var downloadUrl = FileOperater.GetDownloadUrl("f736cf1950 ...
  • EF 更新部分欄位寫法 1、EF預設是查詢出來,修改後保存; 2、設置不修改欄位的IsModified為false,此方法不需要先從資料庫查詢出實體來(最優方法): 3、使用 EntityFramework.Extended 擴展,缺點是EF的上下文日誌不能捕獲執行的sql,此方法也比較麻煩需要逐一 ...
  • 之前有跟第三方通訊合作,應為CRC表碼問題導致校驗出結果不一致,糾結了很久,最後直接採用CRC計算方式校驗才解決。 兩種方式貼,自行對比。 CRC校驗計算方法 查表方法 ...
一周排行
    -Advertisement-
    Play Games
  • 移動開發(一):使用.NET MAUI開發第一個安卓APP 對於工作多年的C#程式員來說,近來想嘗試開發一款安卓APP,考慮了很久最終選擇使用.NET MAUI這個微軟官方的框架來嘗試體驗開發安卓APP,畢竟是使用Visual Studio開發工具,使用起來也比較的順手,結合微軟官方的教程進行了安卓 ...
  • 前言 QuestPDF 是一個開源 .NET 庫,用於生成 PDF 文檔。使用了C# Fluent API方式可簡化開發、減少錯誤並提高工作效率。利用它可以輕鬆生成 PDF 報告、發票、導出文件等。 項目介紹 QuestPDF 是一個革命性的開源 .NET 庫,它徹底改變了我們生成 PDF 文檔的方 ...
  • 項目地址 項目後端地址: https://github.com/ZyPLJ/ZYTteeHole 項目前端頁面地址: ZyPLJ/TreeHoleVue (github.com) https://github.com/ZyPLJ/TreeHoleVue 目前項目測試訪問地址: http://tree ...
  • 話不多說,直接開乾 一.下載 1.官方鏈接下載: https://www.microsoft.com/zh-cn/sql-server/sql-server-downloads 2.在下載目錄中找到下麵這個小的安裝包 SQL2022-SSEI-Dev.exe,運行開始下載SQL server; 二. ...
  • 前言 隨著物聯網(IoT)技術的迅猛發展,MQTT(消息隊列遙測傳輸)協議憑藉其輕量級和高效性,已成為眾多物聯網應用的首選通信標準。 MQTTnet 作為一個高性能的 .NET 開源庫,為 .NET 平臺上的 MQTT 客戶端與伺服器開發提供了強大的支持。 本文將全面介紹 MQTTnet 的核心功能 ...
  • Serilog支持多種接收器用於日誌存儲,增強器用於添加屬性,LogContext管理動態屬性,支持多種輸出格式包括純文本、JSON及ExpressionTemplate。還提供了自定義格式化選項,適用於不同需求。 ...
  • 目錄簡介獲取 HTML 文檔解析 HTML 文檔測試參考文章 簡介 動態內容網站使用 JavaScript 腳本動態檢索和渲染數據,爬取信息時需要模擬瀏覽器行為,否則獲取到的源碼基本是空的。 本文使用的爬取步驟如下: 使用 Selenium 獲取渲染後的 HTML 文檔 使用 HtmlAgility ...
  • 1.前言 什麼是熱更新 游戲或者軟體更新時,無需重新下載客戶端進行安裝,而是在應用程式啟動的情況下,在內部進行資源或者代碼更新 Unity目前常用熱更新解決方案 HybridCLR,Xlua,ILRuntime等 Unity目前常用資源管理解決方案 AssetBundles,Addressable, ...
  • 本文章主要是在C# ASP.NET Core Web API框架實現向手機發送驗證碼簡訊功能。這裡我選擇是一個互億無線簡訊驗證碼平臺,其實像阿裡雲,騰訊雲上面也可以。 首先我們先去 互億無線 https://www.ihuyi.com/api/sms.html 去註冊一個賬號 註冊完成賬號後,它會送 ...
  • 通過以下方式可以高效,並保證數據同步的可靠性 1.API設計 使用RESTful設計,確保API端點明確,並使用適當的HTTP方法(如POST用於創建,PUT用於更新)。 設計清晰的請求和響應模型,以確保客戶端能夠理解預期格式。 2.數據驗證 在伺服器端進行嚴格的數據驗證,確保接收到的數據符合預期格 ...