定义string变量为str,内存流变量为ms,比特数组为bt
1.字符串转比特数组
复制代码 代码如下: (1)byte[] bt=System.Text.Encoding.Default.GetBytes("字符串");
(2)byte[] bt=Convert.FromBase64String("字符串");
2.字符串转流
复制代码 代码如下: (1)MemoryStream ms=new MemoryStream(System.Text.Encoding.Default.GetBytes("字符串"));
(2)MemoryStream ms=new MemoryStream(Convert.FromBase64String("字符串"));
3.流转比特数组
复制代码 代码如下: (1)byte[] bt=ms.ToArray();
(2)MemoryStream ms=new MemoryStream();ms.Write(bt,0,ms.Length);
4.流转字符串
复制代码 代码如下: (1)string str=Convert.ToBase64String(ms.ToArray());
(2)string str=System.Text.Encoding.Default.GetString(ms.ToArray());
5.比特数组转字符串
复制代码 代码如下: (1)string str=System.Text.Encoding.Default.GetString(bt);
(2)string str=Convert.ToBase64String(bt);
6.比特数组转流
复制代码 代码如下: (1)MemoryStream ms=new MemoryStream(bt);
(2)MemoryStream ms=new MemoryStream();ms.Read(bt,0,bt.Length);
总结:可以看出byte[]在字符串string和流MemoryStream之间转换起到过渡的作用,string和MemoryStream转换都要先转换成byte[]。
以下是将文件转为byte[]
/// <summary> /// 将文件转换成byte[] 数组 /// </summary> /// <param name="fileUrl">文件路径文件名称</param> /// <returns>byte[]</returns> protected byte[] GetFileData(string fileUrl) { FileStream fs = new FileStream(fileUrl, FileMode.Open, FileAccess.Read); try { byte[] buffur = new byte[fs.Length]; fs.Read(buffur, 0, (int)fs.Length); return buffur; } catch (Exception ex) { //MessageBoxHelper.ShowPrompt(ex.Message); return null; } finally { if (fs != null) { //关闭资源 fs.Close(); } } } /// <summary> /// 将文件转换成byte[] 数组 /// </summary> /// <param name="fileUrl">文件路径文件名称</param> /// <returns>byte[]</returns> protected byte[] AuthGetFileData(string fileUrl) { using (FileStream fs = new FileStream(fileUrl, FileMode.OpenOrCreate, FileAccess.ReadWrite)) { byte[] buffur = new byte[fs.Length]; using (BinaryWriter bw = new BinaryWriter(fs)) { bw.Write(buffur); bw.Close(); } return buffur; } }