先上一下代码:
我用这个方法意图从一个文本文件中读取其全部内容,以字符串的形式返回。
public string Read(string filepath)
{
string text = "";
FileStream fstream = null;
try
{
if ( false == File.Exists(filepath) )
{
fstream = File.Create(filepath);
}
else
{
fstream = File.OpenRead(filepath);
}
int num = 0;
byte[] buffer = new byte[1024];
UTF8Encoding utf8 = new UTF8Encoding(true);
while ( (num = fstream.Read(buffer, 0, buffer.Length)) > 0 )
{
text += utf8.GetString(buffer);
Array.Clear(buffer, 0, buffer.Length);
}
}
finally
{
if ( null != fstream )
{
fstream.Dispose();
}
}
return text;
}
读取的内容是这样的:
原来的内容是这样的:
在网上搜索了一下,百度上有位仁兄提到了这个问题:https://zhidao.baidu.com/question/100273939.html
然后,把一次读取的字节数改成10240,试了一下,在那两个位置就没有出现乱码了。
byte[] buffer = new byte[10240];
所以应该就是这个原因导致的,不知道有没有办法可以解决这个问题。