我试图写出一个字节[]数组表示一个完整的文件到一个文件。
来自客户端的原始文件通过TCP发送,然后由服务器接收。接收到的流被读入字节数组,然后发送给该类进行处理。
这主要是为了确保接收端的TCPClient已经为下一个流做好了准备,并将接收端与处理端分开。
FileStream类不接受字节数组作为参数或另一个Stream对象(允许向其写入字节)。
我的目标是通过与原始线程(具有TCPClient的线程)不同的线程完成处理。
我不知道如何实现这个,我应该尝试什么?
我试图写出一个字节[]数组表示一个完整的文件到一个文件。
来自客户端的原始文件通过TCP发送,然后由服务器接收。接收到的流被读入字节数组,然后发送给该类进行处理。
这主要是为了确保接收端的TCPClient已经为下一个流做好了准备,并将接收端与处理端分开。
FileStream类不接受字节数组作为参数或另一个Stream对象(允许向其写入字节)。
我的目标是通过与原始线程(具有TCPClient的线程)不同的线程完成处理。
我不知道如何实现这个,我应该尝试什么?
当前回答
是的,为什么不呢?
fs.Write(myByteArray, 0, myByteArray.Length);
其他回答
是的,为什么不呢?
fs.Write(myByteArray, 0, myByteArray.Length);
试试主题:
/// <summary>
/// Convert the Binary AnyFile to Byte[] format
/// </summary>
/// <param name="image"></param>
/// <returns></returns>
public static byte[] ConvertANYFileToBytes(HttpPostedFileBase image)
{
byte[] imageBytes = null;
BinaryReader reader = new BinaryReader(image.InputStream);
imageBytes = reader.ReadBytes((int)image.ContentLength);
return imageBytes;
}
基于问题的第一句话:“我试图写出一个Byte[]数组,表示一个完整的文件到一个文件。”
阻力最小的路径是:
File.WriteAllBytes(string path, byte[] bytes)
记录:
System.IO.File.WriteAllBytes - MSDN
您可以使用文件流。Write(byte[] array, int offset, int count)方法将其写入。
如果你的数组名称是“myArray”,代码将是。
myStream.Write(myArray, 0, myArray.count);
您可以使用BinaryWriter对象。
protected bool SaveData(string FileName, byte[] Data)
{
BinaryWriter Writer = null;
string Name = @"C:\temp\yourfile.name";
try
{
// Create a new stream to write to the file
Writer = new BinaryWriter(File.OpenWrite(Name));
// Writer raw data
Writer.Write(Data);
Writer.Flush();
Writer.Close();
}
catch
{
//...
return false;
}
return true;
}
编辑:哎呀,忘了最后一部分……让我们把它作为一个练习留给读者;-)