guys!
I have a GUI Project in C#, where I add figures, par example: Rectangle, Square etc.
I have to Serialize them in .bin and then Deserialize them and open the figures once again in the GUI . I use [Serializable] and I can save them successfully from the GUI when I start the Application, but when I try to open them in GUI, nothing happens. There are no errors, but nothing shows up.
Here is the Deserialize Code:
MainForm.cs
OpenFileDialog openFileDialog = new OpenFileDialog
{
Filter = "Binary files (*.bin)|*.bin|All files (*.*)|*.*",
DefaultExt = "bin"
};
if (openFileDialog.ShowDialog() == DialogResult.OK)
{
try
{
List<Shape> loadedShapes = SerializationHelper.LoadFromFile(openFileDialog.FileName);
if (loadedShapes != null)
{
ShapeList.Clear();
ShapeList.AddRange(loadedShapes);
statusBar.Items[0].Text = "Last action: Open";
viewPort.Invalidate(); // Refresh the screen to display the new shapes
}
else
{
MessageBox.Show("Failed to load shapes from file.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
catch (Exception ex)
{
MessageBox.Show($"Error while loading file: {ex.Message}", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
and the Method: LoadFromFile:
public static List<Shape> LoadFromFile(string fileName)
{
if (string.IsNullOrEmpty(fileName))
throw new ArgumentNullException(nameof(fileName));
try
{
using (FileStream fs = new FileStream(fileName, FileMode.Open))
{
BinaryFormatter formatter = new BinaryFormatter();
var shapes = (List<Shape>)formatter.Deserialize(fs);
Console.WriteLine($"Loaded {shapes.Count} shapes from {fileName}");
return shapes;
}
}
catch (Exception ex)
{
Console.WriteLine("Error while loading: " + ex.Message);
return null;
}
}
I don’t know what I am doing wrong, tried with GPT but it says the code is OK.