繁体   English   中英

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

[英]Can a Byte[] Array be written to a file in C#?

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

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

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

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

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

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

基于问题的第一句话: “我正在尝试将表示完整文件的 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;
}

编辑:哎呀,忘了finally部分......让我们说它留给读者作为练习;-)

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

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

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

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

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

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

是的,为什么不呢?

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

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

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. 右键单击配置文件文件夹
  2. 转到安全选项卡
  3. 点击“编辑”,
  4. 完全控制“IIS_IUSRS”(如果此用户不存在,则单击添加并键入“IIS_IUSRS”,然后单击“检查名称”。
public ActionResult Document(int id)
    {
        var obj = new CEATLMSEntities().LeaveDocuments.Where(c => c.Id == id).FirstOrDefault();
        string[] stringParts = obj.FName.Split(new char[] { '.' });
        string strType = stringParts[1];
        Response.Clear();
        Response.ClearContent();
        Response.ClearHeaders();
        Response.AddHeader("content-disposition", "attachment; filename=" + obj.FName);
        var asciiCode = System.Text.Encoding.ASCII.GetString(obj.Document);
        var datas = Convert.FromBase64String(asciiCode.Substring(asciiCode.IndexOf(',') + 1));
        //Set the content type as file extension type
        Response.ContentType = strType;
        //Write the file content
        this.Response.BinaryWrite(datas);
        this.Response.End();
        return new FileStreamResult(Response.OutputStream, obj.FType);
    }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM