35

I am trying to deserialize a XML-file. I need to check if the XML-file stream is empty before tying to deserialize it.

IsolatedStorageFileStream isfs1 = new IsolatedStorageFileStream("test.xml", 
    FileMode.Open, FileAccess.Read, isf);

// Deserialize the XML to an object
Settings s = new Settings();
SoapFormatter SF= new SoapFormatter();
s = (Settings) SF.Deserialize(isfs1); 

How can I check if isfs1 empty or not?

John Saunders
  • 160,644
  • 26
  • 247
  • 397
Erik
  • 1,285
  • 2
  • 12
  • 10

5 Answers5

54

Check the Length property of the stream.

Length represents the number of bytes currently in the file.

If it is 0, the file is empty.

Oded
  • 489,969
  • 99
  • 883
  • 1,009
7

If your file is in UTF-8 format, it's size is at least 3 because of BOM(Byte Order Mark). So checking the length > 0 will return true even if your file is empty.

Bogdan
  • 71
  • 1
  • 1
2

Would IsolatedStorageFileStream.Length work?

if (isfs1.Length > 0) {
  // isfs1 isn't empty.
}
King Skippus
  • 3,801
  • 1
  • 24
  • 24
2

If you construct empty zip archive memory stream it have 22 bytes in empty state.

MemoryStream memoryStream = new MemoryStream();
using (ZipArchive zip = new ZipArchive(memoryStream, ZipArchiveMode.Create, true))
{
    // no content added
}
memoryStream.Length // have value of 22
Vasil Valchev
  • 5,701
  • 2
  • 34
  • 39
0

if isfs1.Length =0 means the stream is empty

DeveloperX
  • 4,633
  • 17
  • 22