我正在创建一个查看器。首次转到目录时,通过处理文件、精确映像并将数据序列化为数据文件来创建数据文件。然后,我将新创建的文件反序列化为要查看的表单。第二次转到目录时,它会看到该文件尝试反序列化它以填充表单。当系统必须首先创建它时,它工作正常,但如果它已经在那里,我会收到一个未引用的对象错误。我错过了什么?
private void treeView1_NodeMouseClick(object sender, TreeNodeMouseClickEventArgs e)
{
listView1.Items.Clear();
fileInfoList.Clear();
//fileNameList.Clear();
ClearFlowPanel();
TreeNode newSelected = e.Node;
DirectoryInfo nodeDirInfo = (DirectoryInfo)newSelected.Tag;
dirPath = nodeDirInfo.FullName;
label_selectedPath.Text = dirPath;
foreach (FileInfo file in nodeDirInfo.GetFiles("*.sbs", option))
{
if (file.Extension == ".sbs")
{
fileInfoList.Add(file);
}
}
foreach (FileInfo info in fileInfoList)
{
ListViewItem i = listView1.Items.Add(info.Name, 1);
i.SubItems.Add(SizeInKB(info.Length));
i.SubItems.Add(info.LastWriteTime.ToShortDateString());
}
listView1.AutoResizeColumns(ColumnHeaderAutoResizeStyle.HeaderSize);
string binData = dirPath + "\" + ".browser" + "\" + "_browser.bin";
if (File.Exists(binData))
{
DeserializeData(binData); //creates error
}
}
private void DeserializeData(string binPath)
{
FileStream fs = new FileStream(binPath, FileMode.Open);
BinaryFormatter bin = new BinaryFormatter();
int length = (int)bin.Deserialize(fs);
MessageBox.Show(length.ToString());
for (int i = 0; i < length; i++)
{
viewerData[i] = (ViewerData)bin.Deserialize(fs); //problem
}
for (int i = 0; i < viewerData.Length; i++)
{
PopulateFlowControl(viewerData[i]);
viewerNameList.Add(viewerData[i].name);
}
}
private void UpdateDirectory()
{
thumbPath = dirPath + "\" + ".browser";
if (!Directory.Exists(thumbPath))
{
Directory.CreateDirectory(thumbPath);
}
fileInfoArray = fileInfoList.ToArray();
viewerData = new ViewerData[fileInfoArray.Length];
string binData = thumbPath + "\" + "_browser.bin";
Stream stream = File.Open(binData, FileMode.Create);
BinaryFormatter bin = new BinaryFormatter();
bin.Serialize(stream, fileInfoArray.Length);
ProgressBar_Form progressBar = new ProgressBar_Form(fileInfoArray.Length);
progressBar.Show();
for (int i = 0; i < fileInfoArray.Length; i++)
{
viewerData[i] = new ViewerData(fileInfoArray[i]);
bin.Serialize(stream, viewerData[i]);
progressBar.progressBar1.PerformStep();
progressBar.label_progress.Text = "Processing : " + fileInfoArray[i].Name;
viewerData[i].image.Dispose();
if (File.Exists(viewerData[i].imagePath))
{
File.Delete(viewerData[i].imagePath);
}
}
stream.Close();
progressBar.Close();
DeserializeData(binData); //works fine
}
编辑:
错误:对象引用未设置为对象的实例 - 在反序列化数据(字符串 binPath)中的第一个 for 循环中注释了"问题";
堆栈跟踪...
在 X:\Visual Studio 2010\Projects\Substance Designer\Substance_Browser_12\Substance_Browser_12\Form1.cs:line 151 中的 Substance_Browser_12.Form1.DeserializeData(String binPath) 在 X:\Visual Studio 2010\Projects\Substance Designer\Substance_Browser_12\Substance_Browser_12\Form1.cs:line 133 中的 Substance_Browser_12.Form1.treeView1_NodeMouseClick(Object sender, TreeNodeMouseClickEventArgs e) at System.Windows.Forms.TreeView.OnNodeMouseClick(TreeNodeMouseClickEventArgs e) at System.Windows.Forms.TreeView.WmNotify(Message& m) at System.Windows.Forms.TreeView.WndProc(Message& m) at System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message&m) at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message&m) at System.Windows.Forms.NativeWindow.DebuggableCallback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam) at System.Windows.Forms.UnsafeNativeMethods.SendMessage(HandleRef hWnd, Int32 msg, IntPtr wParam, IntPtr lParam) at System.Windows.Forms.Control.SendMessage(Int32 msg, IntPtr wparam, IntPtr lparam) at System.Windows.Forms.Control.ReflectMessageInternal(IntPtr hWnd, Message&m) at System.Windows.Forms.Control.WmNotify(Message& m) at System.Windows.Forms.Control.WndProc(Message&m) at System.Windows.Forms.ScrollableControl.WndProc(Message& m) at System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message&m) at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message&m) at System.Windows.Forms.NativeWindow.DebuggableCallback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam) at System.Windows.Forms.UnsafeNativeMethods.CallWindowProc(IntPtr wndProc, IntPtr hWnd, Int32 msg, IntPtr wParam, IntPtr lParam) at System.Windows.Forms.NativeWindow.DefWndProc(Message& m) at System.Windows.Forms.Control.DefWndProc(Message& m) at System.Windows.Forms.TreeView.WmMouseDown(Message&m, MouseButton button, Int32 clicks) at System.Windows.Forms.TreeView.WndProc(Message& m) at System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message&m) at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message&m) at System.Windows.Forms.NativeWindow.DebuggableCallback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam) at System.Windows.Forms.UnsafeNativeMethods.DispatchMessageW(MSG& msg) at System.Windows.Forms.Application.ComponentManager.System.Windows.Forms.UnsafeNativeMethods.IMsoComponentManager.FPushMessageLoop(IntPtr dwComponentID, Int32 reason, Int32 pvLoopData) at System.Windows.Forms.Application.ThreadContext.RunMessageLoopInner(Int32 reason, ApplicationContext context) at System.Windows.Forms.Application.ThreadContext.RunMessageLoop(Int32 reason, ApplicationContext context) at System.Windows.Forms.Application.Run(Form mainForm) at Substance_Browser_12.Program.Main() in X:\Visual Studio 2010\Projects\Substance Designer\Substance_Browser_12\Substance_Browser_12\Program.cs:line 18 at System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args) at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args) at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly() 在System.Threading.ThreadHelper.ThreadStart_Context(对象状态) at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx) at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx) at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state) at System.Threading.ThreadHelper.ThreadStart
in msdn BinaryFormatter.Deserialize Method (Stream)
若要成功反序列化,流中的当前位置必须位于对象图的开头。
因此,当您尝试反序列化流中的当前位置时,可能不会在对象图的开头。
您正在将多个 ViewerData 对象序列化为一个文件,但文件中没有这些对象的容器。我认为BinaryFormatter
不支持这种用法。序列化这些对象的替代方法:
- 为每个文件序列化一个查看器数据。
- 将所有 ViewerData 对象添加到集合,然后序列化该集合。如果有许多大图像,则此方法可能会出现内存不足错误。
- 开发一种将
BinaryFormatter
与手动写入/读取相结合的算法,以避免使用过多的内存。这可能需要一个中间流,例如MemoryStream
用于序列化每个查看器数据。请参阅下面的伪代码步骤。
将对象写入文件流的计数。
对于每个对象。 使用 BinaryFormatter 序列化为 MemoryStream。 将内存流写入文件流的长度。 将内存流写入文件流
然后执行反向操作以反序列化对象。
我需要在反序列化数据(字符串binPath)中重新初始化viewerData。如果它来自UpdateDirectory(),它已经是了。
viewerData = new ViewerData[length];
感谢大家的投入!
你只需要改成这个
private void DeserializeData(string binPath)
{
FileStream fs = new FileStream(binPath, FileMode.Open);
fs.Seek(0, SeekOrigin.Begin);
BinaryFormatter bin = new BinaryFormatter();
int length = (int)bin.Deserialize(fs);
MessageBox.Show(length.ToString());
for (int i = 0; i < length; i++)
{
viewerData[i] = (ViewerData)bin.Deserialize(fs); //problem
}
for (int i = 0; i < viewerData.Length; i++)
{
PopulateFlowControl(viewerData[i]);
viewerNameList.Add(viewerData[i].name);
}
}
或
public static System.IO.MemoryStream Serialize(object _Object)
{
System.IO.MemoryStream _Return = new System.IO.MemoryStream();
Serialize(ref _Return, _Object);
return _Return;
}
public static void Serialize(ref System.IO.Stream Stream, object _Object)
{
BinaryFormatter BF = new BinaryFormatter();
BF.Serialize(Stream, _Object);
}
public static objType Deserialize<objType>(ref System.IO.Stream Stream)
{
object _Return = null;
Stream.Seek(0, SeekOrigin.Begin);
BinaryFormatter BF = new BinaryFormatter();
_Return = BF.Deserialize(Stream);
return (objType)_Return;
}