[Webinar] Streamline your web hosting managementRegister Today

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 1769
  • Last Modified:

Write String array to Binary File

I am writing a program to write a heap (multi dimension string array) to a binary file.  Below is the code i wrote to create the binary text file.  How would i go about doing that.  The heap array is called string [,] HeapHold.
static void SaveHeap()// called by Main
        {
            BinaryWriter HeapInput = new BinaryWriter(new FileStream("HeapFile.txt", FileMode.OpenOrCreate));
 
            for (int i = 1; i <= N; i++)
            {
                HeapInput.Write(?????);
            }
 
            WriteToLog.WriteLine("*SaveHeap done - Head has __ nodes");
            WriteToLog.WriteLine();
        }

Open in new window

0
jmkotman
Asked:
jmkotman
  • 3
1 Solution
 
JimBrandleyCommented:
The code below will do it. Note that you need to pass in the dimensions of the array, and you need a separator character that does not appear in your strings. I'm not sure why you are using a BinaryWriter instead of a textWriter.

When you come back later to read the file, you will have to know the number of rows and columns to reconstitute the array.

Jim

// Heap is size[rows,cols]
static void SaveHeap(string[,] heap, int rows, int cols)// called by Main
  {
   char separator = '\n';
      BinaryWriter bw = new BinaryWriter(new FileStream("HeapFile.txt", FileMode.OpenOrCreate));
 
      for (int i = 0; i < rows; i++)
      {
      for (int j = 0; j < cols; j++)
      {
         bw.Write(heap[i, j]);
         bw.Write(separator);
      }
      }
   bw.Flush();
   bw.Close();
 
      WriteToLog.WriteLine("*SaveHeap done - Head has __ nodes");
      WriteToLog.WriteLine();
  }

Open in new window

0
 
JimBrandleyCommented:
You could also write the Rows and Cols values at the start of the file. Then your reader could handle any dimensions.

Jim
0
 
JimBrandleyCommented:
After investigating some more, the separator is not needed. You can do it as below.

Jim

// Heap is size[rows,cols]
static void SaveHeap(string[,] heap, int rows, int cols)// called by Main
{
      BinaryWriter bw = new BinaryWriter(new FileStream("HeapFile.txt", FileMode.OpenOrCreate));
 
      bw.Write(rows);
      bw.Write(cols);
      for (int i = 0; i < rows; i++)
      {
         for (int j = 0; j < cols; j++)
         {
            bw.Write(heap[i, j]);
         }
      }
      bw.Flush();
      bw.Close();
 
      WriteToLog.WriteLine("*SaveHeap done - Head has __ nodes");
      WriteToLog.WriteLine();
}

Open in new window

0

Featured Post

Upgrade your Question Security!

Your question, your audience. Choose who sees your identity—and your question—with question security.

  • 3
Tackle projects and never again get stuck behind a technical roadblock.
Join Now