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

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

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

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

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

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


当前回答

您可以使用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;
}

编辑:哎呀,忘了最后一部分……让我们把它作为一个练习留给读者;-)

其他回答

是的,为什么不呢?

fs.Write(myByteArray, 0, myByteArray.Length);

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

阻力最小的路径是:

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

记录:

System.IO.File.WriteAllBytes - MSDN

您可以使用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;
}

编辑:哎呀,忘了最后一部分……让我们把它作为一个练习留给读者;-)

试试主题:

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

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