检查流是否为空

36

我正在尝试反序列化一个XML文件。我需要在尝试反序列化之前检查XML文件流是否为空。

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); 

我该如何检查 isfs1 是否为空?

5个回答

56

检查流的 Length 属性。

Length 表示当前文件中的字节数。

如果长度为0,则文件为空。


7

如果您的文件以UTF-8格式编码,则由于BOM(字节顺序标记)它的大小至少为3。因此,即使您的文件为空,检查长度> 0也将返回true。


2
那么,有什么解决方案吗? - Ramon Dias

2

2
如果您构建一个空的zip归档内存流,那么在空状态下它将有22个字节。
MemoryStream memoryStream = new MemoryStream();
using (ZipArchive zip = new ZipArchive(memoryStream, ZipArchiveMode.Create, true))
{
    // no content added
}
memoryStream.Length // have value of 22

0

如果 isfs1.Length = 0,则表示流为空。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接