Skip to main content
 首页 » 编程设计

c#之获取写入文件时字符串占用的大小(以字节为单位)

2024年02月05日71linjiqin

我一直在阅读解释如何获取字符串大小、内存大小或文件大小的答案:

我的目的是确定一个字符串在写入文件时以指定编码占用的字节数。

但是,当我检查 Encoding.UTF8、Encoding.Unicode (UTF-16) 或 编码.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