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

0kjbasz6  于 2023-08-08  发布在  .NET
关注(0)|答案(9)|浏览(162)

我试图写出一个代表完整文件的Byte[]数组到一个文件。
来自客户端的原始文件通过TCP发送,然后由服务器接收。接收到的流被读到一个字节数组中,然后发送给这个类进行处理。
这主要是为了确保接收端TCPClient为下一个流做好准备,并将接收端与处理端分开。
FileStream类不接受字节数组作为参数或另一个Stream对象(这允许您向其写入字节)。
我的目标是通过与原始线程不同的线程(使用TCPClient的线程)完成处理。
我不知道如何实现这一点,我应该尝试什么?

raogr8fs

raogr8fs1#

根据问题的第一句话:* “我正在尝试将表示完整文件的Byte[]数组**写入文件。*"
阻力最小的路径是:

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

字符串
此处记录:
System.IO.File.WriteAllBytes - MSDN

km0tfn4u

km0tfn4u2#

您可以使用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部分...让我们说它是留给读者的练习;- )

nhaq1z21

nhaq1z213#

存在静态方法System.IO.File.WriteAllBytes

brccelvz

brccelvz4#

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

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

字符串

vlf7wbxs

vlf7wbxs5#

您可以使用FileStream.Write(byte[] array, int offset, int count)方法将其写出来。
如果你的数组名是“myArray”,代码应该是。

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

字符串

oyt4ldly

oyt4ldly6#

是啊,为什么不呢?

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

字符串

vltsax25

vltsax257#

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

字符串

xam8gpfp

xam8gpfp8#

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用户提供对配置文件文件夹的访问权限。
1.右键单击配置文件文件夹
1.转到安全选项卡
1.点击“编辑”,
1.完全控制“IIS_IUSRS”(如果此用户不存在,则单击“添加”并键入“IIS_IUSRS”,然后单击“检查名称”。

vkc1a9a2

vkc1a9a29#

为了完整起见,System.IO.File.WriteAllBytes()方法还有一个async版本:

Task WriteAllBytesAsync (string path, byte[] bytes, CancellationToken cancellationToken = default);

字符串
示例用法(在async方法中):

await File.WriteAllBytesAsync("C:\\Test.png", bytes);


请注意,由于写入文件是一个IO操作,因此通常必须异步执行,以免阻塞UI。

相关问题