【问题标题】:Can a Byte[] Array be written to a file in C#?可以将 Byte[] 数组写入 C# 中的文件吗?
【发布时间】:2010-09-27 17:54:59
【问题描述】:

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

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

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

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

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

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

【问题讨论】:

    标签: c# .net


    【解决方案1】:

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

    【讨论】:

      【解决方案2】:

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

      【讨论】:

        【解决方案3】:

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

        阻力最小的路径是:

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

        在此记录:

        System.IO.File.WriteAllBytes - MSDN

        【讨论】:

          【解决方案4】:

          您可以使用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 表明它在处理时会进行一些清理。
          • 为什么吞下异常并返回真/假?愚蠢。
          【解决方案5】:

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

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

          【讨论】:

          • 只想添加,写完后添加 bw.flush 和 bw.close
          • @dekdev:在Close() 之前调用Flush() 是没有意义的,因为Close() 将刷新。更好的是使用using 子句,它也会刷新'n'close。
          • 别忘了使用 Dispose;
          【解决方案6】:

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

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

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

          【讨论】:

            【解决方案7】:

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

            【讨论】:

              【解决方案8】:

              是的,为什么不呢?

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

              【讨论】:

                猜你喜欢
                • 1970-01-01
                • 1970-01-01
                • 1970-01-01
                • 1970-01-01
                • 1970-01-01
                • 2022-01-12
                • 2020-09-15
                • 1970-01-01
                • 1970-01-01
                相关资源
                最近更新 更多