C# Stream 和 byte[] 之间的转换

2016-02-19 10:31 1 1 收藏

get新技能是需要付出行动的,即使看得再多也还是要动手试一试。今天图老师小编跟大家分享的是C# Stream 和 byte[] 之间的转换,一起来学习了解下吧!

【 tulaoshi.com - 编程语言 】

/* - - - - - - - - - - - - - - - - - - - - - - - - 
 * Stream 和 byte[] 之间的转换
 * - - - - - - - - - - - - - - - - - - - - - - - */
/// summary
/// 将 Stream 转成 byte[]
/// /summary
public byte[] StreamToBytes(Stream stream)
{
    byte[] bytes = new byte[stream.Length];
    stream.Read(bytes, 0, bytes.Length);

    // 设置当前流的位置为流的开始
    stream.Seek(0, SeekOrigin.Begin);
    return bytes;
}

/// summary
/// 将 byte[] 转成 Stream
/// /summary
public Stream BytesToStream(byte[] bytes)
{
    Stream stream = new MemoryStream(bytes);
    return stream;
}


/* - - - - - - - - - - - - - - - - - - - - - - - - 
 * Stream 和 文件之间的转换
 * - - - - - - - - - - - - - - - - - - - - - - - */
/// summary
/// 将 Stream 写入文件
/// /summary
public void StreamToFile(Stream stream,string fileName)
{
    // 把 Stream 转换成 byte[]
    byte[] bytes = new byte[stream.Length];
    stream.Read(bytes, 0, bytes.Length);
    // 设置当前流的位置为流的开始
    stream.Seek(0, SeekOrigin.Begin);

    // 把 byte[] 写入文件
    FileStream fs = new FileStream(fileName, FileMode.Create);
    BinaryWriter bw = new BinaryWriter(fs);
    bw.Write(bytes);
    bw.Close();
    fs.Close();
}

/// summary
/// 从文件读取 Stream
/// /summary
public Stream FileToStream(string fileName)
{            
    // 打开文件
    FileStream fileStream = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read);
    // 读取文件的 byte[]
    byte[] bytes = new byte[fileStream.Length];
    fileStream.Read(bytes, 0, bytes.Length);
    fileStream.Close();
    // 把 byte[] 转换成 Stream
    Stream stream = new MemoryStream(bytes);
    return stream;
}

来源:https://www.tulaoshi.com/n/20160219/1594924.html

延伸阅读
标签: Web开发
用ADODB.Stream转换,用streamtochar这个函数 HTML html head META http-equiv="Content-Type" content="text/html; charset=Big5" titletest/title SCRIPT LANGUAGE="JavaScript" !-- window.onerror = function (err) { return false;     }; //-- /SCRIPT ...
委托 和 事件 在 .Net Framework中的应用非常广泛,然而,较好地理解委托和事件对很多接触 C# 时间不长的人来说并不容易。它们就像是一道槛儿,过了这个槛的人,觉得真是太容易了,而没有过去的人每次见到委托和事件就觉得心里憋得慌,混身不自在。本文中,我将通过两个范例由浅入深地讲述什么是委托、为什么要使用委托、事件的由来、...
标签: ASP
       欢迎您加入C#的世界!      这一章将把您引进C#的天地,并回答一些相关的问题,如:您为什么要使用C#,C++和C#的主要有什么不同点,以及为什么C#使开发更容易而且还使您感到很有趣。      为什么是另外一种编程语言?      必须回答...
谁说奶爸不靠谱 关爱美妈来证言 “世上只有妈妈好,有妈的孩子像块宝……”这首流传很久的歌谣反映出了普遍心声,从有记忆开始,妈妈才是细心呵护我们的人;印象中的爸爸只有男人的不拘小节和不靠谱的特质。其实他们的内心是温柔的,只是选择默默关爱,尤其从迎接小生命开始,多“不靠谱”的奶爸都会变得细腻起来。 ...
代码: [cpp] const char *cString = "这是一个C字符串, c string"; NSString *nsstring = @"这是个NSString字符串, nsstring"; NSLog(@"cString字符串--%s ",cString); NSLog(@"NSString字符串--%@",nsstring); const char *cString2 = [nsstring UTF8String]; NSString *nsstring2 = [NSString stringWithUTF8String:cString]; NS...

经验教程

489

收藏

98
微博分享 QQ分享 QQ空间 手机页面 收藏网站 回到头部