我试图写出一个字节[]数组表示一个完整的文件到一个文件。

来自客户端的原始文件通过TCP发送,然后由服务器接收。接收到的流被读入字节数组,然后发送给该类进行处理。

这主要是为了确保接收端的TCPClient已经为下一个流做好了准备,并将接收端与处理端分开。

FileStream类不接受字节数组作为参数或另一个Stream对象(允许向其写入字节)。

我的目标是通过与原始线程(具有TCPClient的线程)不同的线程完成处理。

我不知道如何实现这个,我应该尝试什么?


当前回答

有一个静态方法System.IO.File.WriteAllBytes

其他回答

您可以使用文件流。Write(byte[] array, int offset, int count)方法将其写入。

如果你的数组名称是“myArray”,代码将是。

myStream.Write(myArray, 0, myArray.count);

基于问题的第一句话:“我试图写出一个Byte[]数组,表示一个完整的文件到一个文件。”

阻力最小的路径是:

File.WriteAllBytes(string path, byte[] bytes)

记录:

System.IO.File.WriteAllBytes - MSDN

你可以使用System.IO.BinaryWriter来实现这一点,它接受一个流:

var bw = new BinaryWriter(File.Open("path",FileMode.OpenOrCreate);
bw.Write(byteArray);

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用户提供对配置文件文件夹的访问。

右键单击配置文件文件夹 转到安全选项卡 点击“编辑”, 给完全控制"IIS_IUSRS"(如果这个用户不存在,然后点击添加,并键入"IIS_IUSRS",然后点击"检查名称"。

试试主题:

/// <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;
}