简体   繁体   中英

Reading Multiple files in a Byte Array

I have an object that has a byte array property 'ZipFile' to store a file stream:

Property in Result class:

public class Result
{
  public byte[] ZipFile;
}

In my application, I generate a PDF file, and read the file into the 'ZipFile' property using my ReadFile method like this :

objResult.ZipFile = ReadFile(FilePath);

Signature of ReadFile method:

private byte[] ReadFile(string strFileName)

The Problem:

My ReadFile method will now be called in a loop, because I am generating multiple PDF files. Each time the ReadFile method will read a new file from the specifed parameter to the 'objResult.ZipFile' property, consequently replacing the old value in 'ZipFile' property. Now, I want my 'ZipFile' property to store multiple PDF files stream. So what should I do for that? Should I just change this property to a two dimensional byte[][] array, or is there any better way to do this? Remember, that this property will be used for saving(writing) these files by calling method. Open to all Suggestions. Thanks.

Sounds like you should either have a List<Result> , or result should have a collection such as List<byte[]> as a ZipFiles property. Note that currently you don't have a property at all - you have a public field, which is generally a bad idea.

(You probably wouldn't expose it as a List<byte[]> - that would be the underlying implementation. I'd probably make it an IEnumerable<byte[]> and expose an AddZipFile method.)

You may use List<byte[]> (list of byte array) and then append the array in the list in each iteration. Something like.

public class Result
{
   public List<byte[]> ZipFilesList { get; set; };
}

Later you can do:

ResultObj.ZipFilesList.Add(ReadFile(FilePath));

You need to have list of List<byte[]>

public class Result
{
   public List<byte[]> ZipFiles;
}

And add the files into your list

objResult.ZipFiles.Add(ReadFile(FilePath));

If you just want to store them for later processing a list or queue will do it. I think I would opt for a queue as your usage pattern seems to match that.

 // make queue
 var filesQueue = new Queue<byte[]>();

 // add file
 filesQueue.Enqueue(newFile);

 // get file
 var fileToSave=filesQueue.Dequeue();

You can switch to a concurrentQueue later if you would ever need to parallelize etc..

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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