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?
You have to consume the stream to find out if it's empty. That's the point of Stream's semantics (laziness). To check that the stream is not empty you have to attempt to consume at least one element. At that point the stream has lost its "virginity" and cannot be consumed again from the start.
If you use the Apache Commons Collections library in your project, you may use the CollectionUtils. isEmpty and MapUtils. isEmpty() methods which respectively check if a collection or a map is empty or null (i.e. they are "null-safe").
stream(new int[]{}). count()); prints zero. Any stream created from a collection (like a List or Set ) with zero elements can return an empty stream; for example: new ArrayList<Integer>(). stream() returns an empty stream of type Integer .
toList()) , you'll always get an output List (you'll never get null ). If the Stream is empty (and it doesn't matter if it's empty due to the source of the stream being empty, or due to all the elements of the stream being filtered out prior to the terminal operation), the output List will be empty too.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With