我试图写出一个Byte[]数组,表示一个完整的文件到一个文件。
Byte[]
来自客户端的原始文件通过TCP发送,然后由服务器接收。接收到的流被读入字节数组,然后发送给该类进行处理。
这主要是为了确保接收TCPClient为下一个流做好了准备,并将接收端与处理端分开。
TCPClient
FileStream类不接受字节数组作为参数或另一个Stream对象(允许你向它写入字节)。
FileStream
我的目标是通过与原始线程(具有TCPClient的线程)不同的线程完成处理。
我不知道如何实现这个,我应该尝试什么?
是的,为什么不呢?
fs.Write(myByteArray, 0, myByteArray.Length);
基于问题的第一句:"我正在尝试写出一个字节[]数组表示一个完整的文件到一个文件。"
阻力最小的路径是:
File.WriteAllBytes(string path, byte[] bytes)
记录:
System.IO.File.WriteAllBytes - MSDN
System.IO.File.WriteAllBytes
你可以使用BinaryWriter对象。
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; }
编辑:哎呀,忘了finally部分…让我们把它作为一个练习留给读者;-)
finally
你可以使用System.IO.BinaryWriter来实现这一点,它接受一个流,这样:
System.IO.BinaryWriter
var bw = new BinaryWriter(File.Open("path",FileMode.OpenOrCreate); bw.Write(byteArray);
有一个静态方法System.IO.File.WriteAllBytes
你可以使用文件流。写入(byte[] array, int offset, int count)方法把它写出来。
如果你的数组名称是“myArray”,代码将是。
myStream.Write(myArray, 0, myArray.count);
试试主题:
/// <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; }
Asp.net (c#)
//这是服务器路径,应用程序托管在这里。
var path = @"C:\Websites\mywebsite\profiles\";
//字节数组中的文件
var imageBytes = client.DownloadData(imagePath);
/ /文件扩展名
var fileExtension = System.IO.Path.GetExtension(imagePath);
//写入(保存)指定路径上的文件。附加员工id作为文件名和文件扩展名。
File.WriteAllBytes(path + dataTable.Rows[0]["empid"].ToString() + fileExtension, imageBytes);
下一步:
您可能需要为iis用户提供对配置文件文件夹的访问。