File,FileStream,byte[]3者互相转换总结

File>>>FileStream (2种方式)
方式1:
FileStream fs1 = File.Open ( @"D:\集团通知.jpg" , FileMode.Open );
方式2:
FileStream fs2 = new FileStream ( @"D:\通知.jpg" , FileMode.Open );

FileStream>>>byte[]
byte [ ] b1 = new byte [ fs1.Length ];
fs1.Read ( b1 , 0 , b1.Length );

把文件保存到数据库中一般是File>>>FileStream>>>byte[]

byte[]>>>File(2种方式)
假设byte[ ] b1里面有数据
方式1:
File.WriteAllBytes ( @"D:\通知b2.jpg" , b1 );
方式2:
FileStream fs = new FileStream ( @"D:\通知b_2.jpg" , FileMode.OpenOrCreate , FileAccess.Write );
fs.Write ( b1 , 0 , b1.Length );
fs.Close ( );

FileStream>>>FileStream
有时需要把文件流写到ftp的请求流中,实际上是利用byte[]做了一个缓冲区
Stream requestStream = uploadRequest.GetRequestStream ( );
FileStream fileStream =  File.Open ( @"D:\abc.txt" , FileMode.Open );

byte [ ] buffer = new byte [ 1024 ];
int bytesRead;
while ( true )
{
bytesRead = fileStream.Read ( buffer , 0 , buffer.Length );
if ( bytesRead == 0 )
break;
requestStream.Write ( buffer , 0 , bytesRead );
}



posted on 2011-05-18 09:35  jianshaohui  阅读(373)  评论(1编辑  收藏  举报

导航