2017-10-04 32 views
-1

如果我从文件中读取字节数组,并使用下面的代码字节数组不同

byte[] bytes = File.ReadAllBytes(filePath); 

    File.WriteAllBytes(filePath, byteArr); 

作品完美fine.I可以打开并查看它写正确写入文件。

但是,如果我读文件内容到一个字符串,然后使用以下函数

string s = File.ReadAllText(filePath); 
    var byteArr = System.Text.Encoding.UTF8.GetBytes(s); 

字节阵列的尺寸是大于先前的阵列直接从文件中读取其转换为字节阵列和值也不同,因此,如果我写使用此阵列打开

注意当不能读取该文件: -文件是UTF-8编码 我发现,使用以下代码

using (StreamReader reader = new StreamReader(filePath, Encoding.UTF8, true)) 
     { 
      reader.Peek(); // you need this! 
      var encoding = reader.CurrentEncoding; 
     } 

无法理解为什么两个阵列不同?

我是使用下面的附加的图像转换,然后写

image

+2

你在这里期待什么?在图像文件上使用ReadAlltext()没有任何意义。 –

+0

需要保存文件可能是任何图像或文本.. –

+0

我是uisng filestream来保存文件数据,并且需要在需要时检索文件 –

回答

2

随着

using (StreamReader reader = new StreamReader(filePath, Encoding.UTF8, true)) 
{ 
    reader.Peek(); // you need this! 
    var encoding = reader.CurrentEncoding; 
} 

var encoding只会呼应Encoding.UTF8参数。你在那里欺骗你自己。

二进制文件只是没有文本编码。


需要保存文件可能是任何图像或文本

就用ReadAllBytes/WriteAllBytes。文本文件始终也是byte[],但并非所有文件类型都是文本。您需要首先使用Base64编码,并且只是增加了大小。

1

将字节数组转换为字符串最安全的方法的确将其编码为base64之类的东西。 Like:

string s = Convert.ToBase64String(bytes);

byte [] bytes = Convert.FromBase64String(s);

相关问题