I used this code to serialize:
using System;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
[Serializable]
public class Car
{
public string Make;
public string Model;
public uint Year;
public byte Color;
}
public class Exercise
{
static void Main(string[] args)
{
Car vehicle = new Car();
vehicle.Make = "Lexus";
vehicle.Model = "LS";
vehicle.Year = 2007;
vehicle.Color = 4;
FileStream stmCar = new FileStream("Car3.car", FileMode.Create);
BinaryFormatter bfmCar = new BinaryFormatter();
bfmCar.Serialize(stmCar, vehicle);
}
}
and program creating without problems file car3.car.
But when I used this program to desesrialize:
using System;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
[Serializable]
public class Car
{
public string Make;
public string Model;
public uint Year;
public byte Color;
}
class Program
{
static void Main(string[] args)
{
FileStream stmCar = new FileStream("Car3.car", FileMode.Open);
BinaryFormatter bfmCar = new BinaryFormatter();
//1 Car vehicle = (Car)bfmCar.Deserialize(stmCar);
Console.WriteLine("Make: {0}", vehicle.Make);
Console.WriteLine("Model: {0}", vehicle.Model);
Console.WriteLine("Year: {0}", vehicle.Year);
Console.Write("Color: ");
byte clr = vehicle.Color;
switch (clr)
{
case 1:
Console.WriteLine("Black");
break;
case 2:
Console.WriteLine("Gray");
break;
case 3:
Console.WriteLine("White");
break;
case 4:
Console.WriteLine("Red");
break;
case 5:
Console.WriteLine("Blue");
break;
}
stmCar.Close();
}
}
I get error in line //1 "System.IO.FileNotFoundException was unhandled Message="Could not find file 'E:\\WindowsCS\\Learning CSharp\\Test21\\bin\\Debug\\Car3.car'."
Source="mscorlib"
FileName="E:\\WindowsCS\\Learning CSharp\\Test21\\bin\\Debug\\Car3.car"
StackTrace:
at System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath)
at System.IO.FileStream.Init(String path, FileMode mode, FileAccess access, Int32 rights, Boolean useRights, FileShare share, Int32 bufferSize, FileOptions options, SECURITY_ATTRIBUTES secAttrs, String msgPath, Boolean bFromProxy)
at System.IO.FileStream..ctor(String path, FileMode mode)
at Test21.Program.Main(String[] args) in E:\WindowsCS\Learning CSharp\Test21\Program.cs:line 20
at System.AppDomain._nExecuteAssembly(Assembly assembly, String[] args)
at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
at System.Threading.ThreadHelper.ThreadStart()
I tried to make this file work, but I didin't understand what must I do. Please help.