Checking if a stream is empty
Asked Answered
G

5

36

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?

Gaudet answered 30/5, 2011 at 19:5 Comment(0)
M
58

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.

Municipalize answered 30/5, 2011 at 19:9 Comment(0)
R
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.

Rarely answered 24/7, 2014 at 15:41 Comment(1)
so? what's the solution?Alfieri
R
2

Would IsolatedStorageFileStream.Length work?

if (isfs1.Length > 0) {
  // isfs1 isn't empty.
}
Roberts answered 30/5, 2011 at 19:10 Comment(0)
O
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
Obvert answered 18/6, 2021 at 12:34 Comment(0)
C
0

if isfs1.Length =0 means the stream is empty

Corn answered 30/5, 2011 at 19:16 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.