ChatGPT解决这个技术问题 Extra ChatGPT

可以将 Byte[] 数组写入 C# 中的文件吗?

我正在尝试将表示完整文件的 Byte[] 数组写入文件。

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

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

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

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

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


K
Kev

基于问题的第一句话:“我正在尝试将表示完整文件的 Byte[] 数组写入文件。”

阻力最小的路径是:

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

记录在这里:

System.IO.File.WriteAllBytes - MSDN


O
Odys

您可以使用 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 部分...可以说它留给读者作为练习 ;-)


可以说,我收到了压缩数据,并将其解压缩为 Byte[]。是否可以使用上述功能重新创建文件?有在线教程或演示吗?
@buffer_overflow:如果要取回原始文件,则需要先对其进行压缩。查看装饰器模式以了解可能的实现:en.wikipedia.org/wiki/Decorator_pattern
BinaryWriter 是一次性的,因此可能应该在 using 块中使用。这也意味着您可能会放弃一些额外的调用,因为 source code 表明它在处理时会进行一些清理。
为什么吞下异常并返回真/假?愚蠢。
A
Andrew Rollings

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


S
Soner Gönül

您可以使用采用 Stream 的 System.IO.BinaryWriter 来执行此操作:

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

只想添加,写完后添加 bw.flush 和 bw.close
@dekdev:在 Close() 之前调用 Flush() 毫无意义,因为 Close() 将刷新。更好的是使用 using 子句,它也将刷新'n'close。
不要忘记使用 Dispose;
M
Mitchel Sellers

您可以使用 FileStream.Write(byte[] array, int offset, int count) 方法将其写出。

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

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

m
mmx

是的,为什么不呢?

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

G
Graham

尝试 BinaryReader:

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

M
Muhammad Kashif Khan

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”并单击“检查名称”。