C# Stream 和 byte[] 之间的转换
程序员文章站
2023-11-18 16:44:40
/* - - - - - - - - - - - -...
/* - - - - - - - - - - - - - - - - - - - - - - - -
* 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;
}
* 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;
}
下一篇: C#从实体对象集合中导出Excel的代码
推荐阅读