1

I save a List of my class into a binary file and use FileStream and BinaryFormatter.

private void SaveCustomers()
{
  FileStream fs = null;

  try
  {
    fs = new FileStream( Application.StartupPath + dataPath + @"\" + customersFilename, FileMode.Create, FileAccess.Write );
    BinaryFormatter bf = new BinaryFormatter();
    bf.Serialize(fs, customers);

  }
  catch (Exception ex)
  {
    MessageBox.Show( ex.Message, "Fehler beim speichern der Besucherdaten", MessageBoxButtons.OK, MessageBoxIcon.Error );
  }
  finally
  {
    if (fs != null)
    {
      fs.Flush();
      fs.Close();
    }
  }
}

At some point in my programm the file gets "destroyed". Since this is the only methode with the right to write in the file I think this methode is the problem.

My assumption is that the BinaryFormatter is not finished when the Filestream gets flushed and closed.

It only happend lately since the file is around 8 MB at the beginning it worked flawless.

Am I right in my assumption? or is it completly different.

private void LoadCustomers()
{
  FileStream fs = null;

  try
  {
    fs = new FileStream( Application.StartupPath + dataPath + @"\" + customersFilename, FileMode.OpenOrCreate, FileAccess.Read );
    BinaryFormatter bf = new BinaryFormatter();
    customers = (List<Customer>)bf.Deserialize( fs );

    if (customers == null) customers = new List<Customer>();
  }
  catch (Exception ex)
  {
    MessageBox.Show( ex.Message, "Fehler beim laden der Besucherdaten", MessageBoxButtons.OK, MessageBoxIcon.Error );
  }
  finally
  {
    if (fs != null)
    {
      fs.Flush();
      fs.Close();
    }
  }
}

The last code is my reader.

F. Aker
  • 27
  • 1
  • 9
  • 1
    Whatever is in your `finally` block will execute **after** everything inside `try` and `catch`. Hence `finally`.. it happens **last**. – ThePerplexedOne Dec 07 '16 at 11:11
  • I agree with @ThePerplexedOne - as long as you don't serialize asyncron the data will be written into your file. But what do you mean by: "the file gets destroyed" ? Wrong data? File deleted? Something different? I mean FileMode.Create will create or overwrite your file if I am right,... If this is a Kind of logfile, I guess this is not what u want to do... If you want to append use `FileMode.Append` or `FileMode.OpenOrCreate` – TripleEEE Dec 07 '16 at 11:20
  • Try deleting the file before writing. I had an issue where I wrote into a file with `FileMode.Create` and it did not properly truncate before causing the file to hold invalid data. Deleting before writing fixed it. – Mats391 Dec 07 '16 at 11:49
  • before writing it is close to 8 MB big and after only 7KB i didn't change the data. and i can not read the file afterwards – F. Aker Dec 07 '16 at 11:52
  • Such an API would be unusable. It's not like that. The bug is elsewhere and not in the code posted AFAICT. – usr Dec 07 '16 at 13:45

1 Answers1

0

You use FileMode.Create which causes your program to overwrite your file when it exists already. (I guess this is what you mean by "the file gets destroyed".

You rather should use FileMode.OpenOrCreate if you want to add new lines, like in a logfile...

See: MSDN Create:

Specifies that the operating system should create a new file. If the file already exists, it will be overwritten. This requires FileIOPermissionAccess.Write permission. FileMode.Create is equivalent to requesting that if the file does not exist, use CreateNew; otherwise, use Truncate. If the file already exists but is a hidden file, an UnauthorizedAccessException exception is thrown.

TripleEEE
  • 499
  • 3
  • 11
  • i have all information i need in a list and need all in a file. if i use openorcreate does it check what changed ? – F. Aker Dec 07 '16 at 11:39
  • If you go with `OpenOrCreate` it will go and append data to your FileStream related file. You want to overwrite your old Information? If so, `Create` is right, as you used it. So as you have written when you file get bigger then 8MB your file is written like with 8Kb? Is there an error shown in your messagebox when this happens? – TripleEEE Dec 07 '16 at 11:58
  • an error occurs if i try to load the file at another point later. there ist no exception throws while i try to safe it. the error while reading is something like: streamoverflow while loading data ( free translated ) – F. Aker Dec 07 '16 at 12:03
  • Well as I understand it, your code is fine - without more detailed error in reading the file, or maybe an exception we can't help you any further. Maybe there is something wrong with your customers List? – TripleEEE Dec 07 '16 at 12:37
  • Now the exact error while reading is: The streamend was reached before the processing was finished. – F. Aker Dec 07 '16 at 12:44
  • Can you provide your StreamReader Code please? Because to me it seems like you're Reader corrupts the file when reading which will lead to your 8kB corrupt file. – TripleEEE Dec 07 '16 at 12:47
  • i added the reader code to my question. but for me it looks like the writing is the problem since the file are only 1/1000 of the size afterwards. and the reader only has the right to read. Thank you – F. Aker Dec 07 '16 at 13:03
  • Mh, you might want to try out this: http://stackoverflow.com/questions/306596/end-of-stream-encountered-before-parsing-was-completed I am not exactly sure if this helps, but i suggest you give it a try – TripleEEE Dec 07 '16 at 13:16