title: Deserialize object from binary file
body: <p>Hey guys I am working on a program that will take a person's name and comment and then serialize it to a binary file. It must also be able to deserialize and load the data to the form. I need it to be able to go up and down the list of files(names and comments) by using buttons on the form.
  In my code I have it separated into a class that builds the object and the code for the form, and no i'm not allowed to separate it. (Just in case anyone thought that'd work)<br>
  the form code:</p>
  
  <pre><code>private void btnAdd_Click(object sender, EventArgs e)
  {
      bool blnValid = true;
      if (string.IsNullOrWhiteSpace(txtName.Text))
      {
          MessageBox.Show("Please enter a valid name");
      }
      if (string.IsNullOrWhiteSpace(txtComment.Text))
      {
          MessageBox.Show("Please enter a valid comment");
          blnValid = false;
      }
  
      if (blnValid)
      {
          //create class instance and assign property values
          //set file name
  
          DateTime CurrentDate = DateTime.Now;
          string strFileName;
  
          strFileName = CurrentDate.ToString("dd-MM-yy-hh-mm-ss") + ".bin";
  
          // serialize object to binary file
  
          MessageBox.Show(strFileName);
  
          Enquiry newEnquiry = new Enquiry();
          newEnquiry.Name = txtName.Text;
          newEnquiry.Comment = txtComment.Text;
          newEnquiry.DOB = dteDOB.Value;
          newEnquiry.WriteToFile(strFileName, newEnquiry);
      }
  }
  
  private void btnLoad_Click(object sender, EventArgs e)
  {
  
  }
  
  private void btnPrevious_Click(object sender, EventArgs e)
  {
  
  }
  </code></pre>
  
  <p>and the class code:</p>
  
  <pre><code>[Serializable]
  class Enquiry
  {
      //stores the various values into the enquiry class.
      public string Name { get; set; }
  
      public DateTime DOB { get; set; }
  
      public string Comment { get; set; }
  
      //creates the file, if there isn't one, writes the file, and
      //disables sharing while the program is active. It also formats
      //the file into binary 
      public void WriteToFile(string strFileName, Enquiry newEnquiry)
      {
          IFormatter formatter = new BinaryFormatter();
          Stream stream = new FileStream(strFileName, FileMode.Create, FileAccess.Write, FileShare.None);
          formatter.Serialize(stream, newEnquiry);
          stream.Close();
  
      }
      // this loads the files and translates them to plain text
  
      public void ReadFromFile(string strFileName, Enquiry newEnquiry)
      {
          Stream stream = File.OpenRead(strFileName);
          BinaryFormatter formatter = new BinaryFormatter();
          newEnquiry = (Enquiry)formatter.Deserialize(stream);
          stream.Close();     
      }
  </code></pre>