Usually Type Converter In Socket Transfor

As a chsarp developer ,you must  have learned the socket ,and you know that the data transfor by network should be rely on byte or xml .

There I will give the usually type converter in socket transfor

 

1:string byte[]          (use to fransfor message in socket)

(1):string convert to byte[]

string str="wulong";

byte[] byteArray = System.Text.Encoding.Default.GetBytes(str);

//you also could select your own encode accoding to the requirement of project

 

(2)byte[] convert to string

byte[] byteArray;//you can get it by the socket,then convert to string

string str = System.Text.Encoding.Default.GetString(byteArray);

 

2:File byte[]          (use to file transfor in socket)

(1):File to byte[] 

string fileName="";

 FileStream fileStream = new FileStream(fileName, FileMode.Open, FileAccess.Read);

 BinaryReader binaryReader = new BinaryReader(fileStream);

 binaryReader.BaseStream.Seek(0, SeekOrigin.Begin);   

  byte[]  bytes= binaryReader.ReadBytes((int)binaryReader.BaseStream.Length);


(2):byte[] to filestream

 byte[] bytes;

 FileStream fileStream = new FileStream(fileName, FileMode.Open, FileAccess.Read);

 fileStream .Write(bytes, 0, bytes.Length);

  

then you could deal with the fileStream

  

3:Image byte[]  (use transfor image in socket)

(1):Image to byte[]

            Image image = Image.FromFile("filepath");
            MemoryStream ms = new MemoryStream();
            image.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
            byte[] byteImage = ms.GetBuffer();

(2):byte[] to Image

            byte[] byteImage;

            MemoryStream   ms = new MemoryStream(byteImage);
            Image imageGetByBytes = Image.FromStream(ms);

 



 

 

 

 

 

 

转载于:https://www.cnblogs.com/WuLong/archive/2010/11/19/1882220.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值