![](/img/trans.png)
[英]Get the size of the file(in bytes) currently written by the StreamWriter
[英]Get the size, in bytes, of how much a string will occupy when written to a file?
我一直在閱讀解釋如何獲取字符串大小,內存大小或文件大小的答案:
我的意圖是確定在寫入文件時,字符串將以指定的編碼占用的字節數。
但是,當我檢查Encoding.UTF8
, Encoding.Unicode
(UTF-16)或Encoding.UTF32
的字符串大小時,我的函數沒有返回預期的結果。
這就是我在做什么:
''' ----------------------------------------------------------------------
''' <summary>
''' Gets the size, in bytes, of how much a string will occupy when written to a file.
''' </summary>
''' ----------------------------------------------------------------------
<DebuggerStepThrough>
<Extension>
Public Function SizeInFile(ByVal sender As String,
Optional ByVal encoding As Encoding = Nothing) As Integer
If (encoding Is Nothing) Then
encoding = System.Text.Encoding.Default
End If
Return encoding.GetByteCount(sender)
End Function
這就是我測試的方式,在下面的代碼中,該函數說字符串大小為2個字節,但是當寫入文件時,文件大小為4個字節:
Dim str As String = "Ñ"
Console.WriteLine(String.Format("Size of String : {0}", str.SizeInFile(Encoding.Unicode)))
File.WriteAllText(".\Test.txt", str, Encoding.Unicode)
Console.WriteLine(String.Format("Size of txtfile: {0}", New FileInfo(".\Test.txt").Length))
我缺少有效評估字符串大小的內容嗎?
在C#或VB.NET中。
文件可以以字節順序標記(稱為BOM)開頭,該標記可以幫助讀者檢測所使用的編碼。
UTF8的BOM為3字節EF,BB,BF
對於UTF16(Encoding.Unicode)2字節FEFF(根據編碼方式編碼為大端或小端)
對於UTF32 4字節0000FEFF
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.