当前位置: 移动技术网 > IT编程>开发语言>c# > C# Stream 和 byte[] 之间的转换

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

2019年07月18日  | 移动技术网IT编程  | 我要评论
/* - - - - - - - - - - - -
/* - - - - - - - - - - - - - - - - - - - - - - - - 
 * 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;
}

如您对本文有疑问或者有任何想说的,请点击进行留言回复,万千网友为您解惑!

相关文章:

验证码:
移动技术网