我想知道是否有办法告诉.NET中字符串的大小(文件大小)。想象一下,你有一个文本句子,接收系统需要限制它收到的文本的大小。
有没有办法告诉字符串的大小(以字节或KB为单位)还是只读取UTF-8编码字符串的前N个字节或KB?
string testSentence =“我只想要这句话的前2 KB。是否可以将其拆分为2 KB序列的块,这样我就可以循环并一次发送2 KB到另一个进程?”
答案 0 :(得分:3)
您可以使用Encoding.UTF8.GetBytes
将字符串转换为字节。然后将字节拆分为2048字节块。小心不要将一个字符分成两个块。
byte[] bytes = Encoding.UTF8.GetBytes(testSentence);
int pos = 0;
int length = bytes.Length;
while (length > 0)
{
int count = 2048;
if (count >= length) // last chunk
{
// send chunk
Send(bytes, pos, length);
pos += length;
length -= length;
}
else // not last chunk
{
// chop off last character
while ((bytes[pos + count - 1] & 0xC0) == 0x80) count--;
count--;
// send chunk
Send(bytes, pos, count);
pos += count;
length -= count;
}
}
(未测试的)
答案 1 :(得分:0)
使用方法System.Text.Encoding.UTF8.GetByteCount()。
(答案已编辑。)
答案 2 :(得分:0)
我认为类似于以下内容会提供您正在寻找的东西..
byte[] data = System.Text.Encoding.UTF8.GetBytes(theString).Take(2048).ToArray();
或
byte[] source = System.Text.Encoding.UTF8.GetBytes(theString);
byte[] destination = new byte[2048];
Buffer.BlockCopy(source, 0, destination, 0, 2048);
编辑:添加评论示例..
这将为您提供List<byte[]>
个2KB的块,值得注意的是,这不是为了提高效率而是为了示例目的,尽管它可以完成工作,但不会针对高性能进行调整。< / p>
string theString = new string('*', 1022574);
byte[] allData = System.Text.Encoding.UTF8.GetBytes(theString);
int numberOfChunks = (int)Math.Ceiling((double)(allData.Length) / 2048);
List<byte[]> chunks = new List<byte[]>(numberOfChunks);
for (int i = 0; i < numberOfChunks; i++) {
chunks.Add(allData.Skip(i * 2048).Take(2048).ToArray());
}