我使用BinaryFormatter
,我序列化了一个树视图。
现在我想为ImageList
我使用此代码序列化:
public static void SerializeImageList(ImageList imglist)
{
FileStream fs = new FileStream("imagelist.iml", FileMode.Create);
BinaryFormatter bf = new BinaryFormatter();
bf.Serialize(fs, imglist.ImageStream);
fs.Close();
}
这个要反序列化:
public static void DeSerializeImageList(ref ImageList imgList)
{
FileStream fs = new FileStream("imagelist.iml", FileMode.Open);
BinaryFormatter bf = new BinaryFormatter();
imgList.ImageStream = (ImageListStreamer)bf.Deserialize(fs);
fs.Close();
}
但是我在所有键中都得到一个空字符串!!
ImgList.Images.Keys
为什么?
答案 0 :(得分:0)
大多数人并没有使用他们的全部资源来交叉引用他们已经知道的东西。 ImageList
目前的形式不可序列化,但您真正想要保存的只有两件事,那就是Key
和Image
。所以你构建了一个中间类来保存它们,这是可序列化的,如下例所示:
[Serializable()]
public class FlatImage
{
public Image _image { get; set; }
public string _key { get; set; }
}
void Serialize()
{
string path = Options.GetLocalPath("ImageList.bin");
BinaryFormatter formatter = new BinaryFormatter();
List<FlatImage> fis = new List<FlatImage>();
for (int index = 0; index < _smallImageList.Images.Count; index++)
{
FlatImage fi = new FlatImage();
fi._key = _smallImageList.Images.Keys[index];
fi._image = _smallImageList.Images[index];
fis.Add(fi);
}
using (FileStream stream = File.OpenWrite(path))
{
formatter.Serialize(stream, fis);
}
}
void Deserialize()
{
string path = Options.GetLocalPath("ImageList.bin");
BinaryFormatter formatter = new BinaryFormatter();
try
{
using (FileStream stream = File.OpenRead(path))
{
List<FlatImage> ilc = formatter.Deserialize(stream) as List<FlatImage>;
for( int index = 0; index < ilc.Count; index++ )
{
Image i = ilc[index]._image;
string key = ilc[index]._key;
_smallImageList.Images.Add(key as string, i);
}
}
}
catch { }
}