• 博客园logo
  • 会员
  • 周边
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
FtpCsharp
博客园    首页    新随笔    联系   管理    订阅  订阅

Usually Type Converter In Socket Transfor

Usually Type Converter In Socket Transfor 1:string byte[] (use to fransfor message in socket) 2:File byte[] (use to file transfor in socket) 3:Image byte[] (use transfor image in socket)

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);

 



 

 

 

 

 

 

posted @ 2010-11-19 22:16  FtpCsharp  阅读(425)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3