本文整理汇总了C#中System.Runtime.Serialization.Formatters.Binary.BinaryFormatter类的典型用法代码示例。如果您正苦于以下问题:C# BinaryFormatter类的具体用法?C# BinaryFormatter怎么用?C# BinaryFormatter使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
BinaryFormatter类属于System.Runtime.Serialization.Formatters.Binary命名空间,在下文中一共展示了BinaryFormatter类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: ToBytes
/// <summary>
/// 将一个对象序列化为字节数组
/// </summary>
/// <param name="data">要序列化的对象</param>
/// <returns>序列化好的字节数组</returns>
public static byte[] ToBytes(Object data)
{
MemoryStream ms = new MemoryStream();
BinaryFormatter bf = new BinaryFormatter();
bf.Serialize(ms, data);
return ms.ToArray();
}
示例2: Show
protected override void Show(IDialogVisualizerService windowService, IVisualizerObjectProvider provider)
{
using (Form form1 = new Form())
{
form1.Text = "FormCollection Visualizer";
form1.StartPosition = FormStartPosition.WindowsDefaultLocation;
form1.SizeGripStyle = SizeGripStyle.Auto;
form1.ShowInTaskbar = false;
form1.ShowIcon = false;
DataTable dt;
using (Stream stream = provider.GetData())
{
BinaryFormatter bformatter = new BinaryFormatter();
dt = (DataTable)bformatter.Deserialize(stream);
stream.Close();
}
DataGridView gridView = new DataGridView();
gridView.Dock = DockStyle.Fill;
form1.Controls.Add(gridView);
gridView.DataSource = dt;
windowService.ShowDialog(form1);
}
}
示例3: LoadState
/// <summary>
/// Opens a bin-file and converts it to a SaveFile that gets returned.
/// </summary>
public SaveFile LoadState()
{
SaveFile tmpFile = new SaveFile();
Stream fileStreamer;
BinaryFormatter bf;
try
{
using(fileStreamer = File.Open("state.bin", FileMode.Open))
{
bf = new BinaryFormatter();
var tmpState = bf.Deserialize(fileStreamer);
tmpFile = (SaveFile)tmpState;
return tmpFile;
}
}
catch
{
return tmpFile;
}
}
示例4: SerializeToStream
public static MemoryStream SerializeToStream(object o)
{
MemoryStream stream = new MemoryStream();
IFormatter formatter = new BinaryFormatter();
formatter.Serialize(stream, o);
return stream;
}
示例5: TestVFSException
public void TestVFSException()
{
var e1 = new VFSException();
Assert.IsTrue(e1.Message.Contains("VFSException"));
var e2 = new VFSException("a");
Assert.AreEqual("a", e2.Message);
var e3 = new VFSException("a", new Exception("x"));
Assert.AreEqual("a", e3.Message);
Assert.AreEqual("x", e3.InnerException.Message);
using (var ms = new MemoryStream())
{
var serializer = new BinaryFormatter();
serializer.Serialize(ms, e3);
ms.Seek(0, SeekOrigin.Begin);
var e4 = serializer.Deserialize(ms) as VFSException;
Assert.IsNotNull(e4);
Assert.AreEqual("a", e4.Message);
Assert.AreEqual("x", e4.InnerException.Message);
}
}
示例6: CreateCrashDump
/// <summary>
/// Creates the crash dump.
/// </summary>
public static void CreateCrashDump()
{
if (!Directory.Exists("Dumps"))
Directory.CreateDirectory("Dumps");
Log.Info("Creating crash dump...");
try
{
using (var fs =
File.Open(
Path.Combine(Environment.CurrentDirectory, "Dumps",
string.Format("{0}.acd", DateTime.Now.ToString("yyyy_MM_dd_HH_mm"))),
FileMode.Create))
{
var formatter = new BinaryFormatter();
var bot = AlarisBot.Instance;
formatter.Serialize(fs, bot);
}
}
catch(Exception x)
{
Log.Fatal("Failed to write crash dump. ({0})", x);
return;
}
Log.Info("Crash dump created.");
}
示例7: TestRoundTripElementSerialisation
public void TestRoundTripElementSerialisation()
{
// Use a BinaryFormatter or SoapFormatter.
IFormatter formatter = new BinaryFormatter();
//IFormatter formatter = new SoapFormatter();
// Create an instance of the type and serialize it.
var elementId = new SerializableId
{
IntID = 42,
StringID = "{BE507CAC-7F23-43D6-A2B4-13F6AF09046F}"
};
//Serialise to a test memory stream
var m = new MemoryStream();
formatter.Serialize(m, elementId);
m.Flush();
//Reset the stream
m.Seek(0, SeekOrigin.Begin);
//Readback
var readback = (SerializableId)formatter.Deserialize(m);
Assert.IsTrue(readback.IntID == 42);
Assert.IsTrue(readback.StringID.Equals("{BE507CAC-7F23-43D6-A2B4-13F6AF09046F}"));
}
示例8: logon
public Constants.LoginStatus logon(User user)
{
Constants.LoginStatus retval = Constants.LoginStatus.STATUS_SERVERNOTREACHED;
byte[] message = new byte[Constants.WRITEBUFFSIZE];
byte[] reply;
MemoryStream stream = new MemoryStream(message);
try
{
//Serialize data in memory so you can send them as a continuous stream
BinaryFormatter serializer = new BinaryFormatter();
NetLib.insertEntropyHeader(serializer, stream);
serializer.Serialize(stream, Constants.MessageTypes.MSG_LOGIN);
serializer.Serialize(stream, user.ringsInfo[0].ring.ringID);
serializer.Serialize(stream, user.ringsInfo[0].userName);
serializer.Serialize(stream, user.ringsInfo[0].password);
serializer.Serialize(stream, user.node.syncCommunicationPoint);
reply = NetLib.communicate(Constants.SERVER2,message, true);
stream.Close();
stream = new MemoryStream(reply);
NetLib.bypassEntropyHeader(serializer, stream);
Constants.MessageTypes replyMsg = (Constants.MessageTypes)serializer.Deserialize(stream);
switch(replyMsg)
{
case Constants.MessageTypes.MSG_OK:
ulong sessionID = (ulong)serializer.Deserialize(stream);
uint numRings = (uint)serializer.Deserialize(stream);
uint ringID;
Ring ring;
for(uint ringCounter = 0; ringCounter < numRings; ringCounter++)
{
LordInfo lordInfo = (LordInfo)serializer.Deserialize(stream);
ring = RingInfo.findRingByID(user.ringsInfo, lordInfo.ringID);
ring.lords = lordInfo.lords;
}
user.loggedIn = true;
retval = Constants.LoginStatus.STATUS_LOGGEDIN;
break;
case Constants.MessageTypes.MSG_NOTAMEMBER:
retval = Constants.LoginStatus.STATUS_NOTAMEMBER;
break;
case Constants.MessageTypes.MSG_ALREADYSIGNEDIN:
retval = Constants.LoginStatus.STATUS_ALREADYSIGNEDIN;
break;
default:
break;
}
}
catch (Exception e)
{
int x = 2;
}
return retval;
}
示例9: Save
public void Save(string path)
{
BinaryFormatter binaryFormatter = new BinaryFormatter();
FileStream fileStream = new FileStream(path, FileMode.Create, FileAccess.Write);
binaryFormatter.Serialize(fileStream, this);
fileStream.Close();
}
示例10: talk
public bool talk()
{
try
{
if (null != sendPro)
{
TcpClient client = new TcpClient();
client.Connect(IPAddress.Parse(ClientInfo.confMap.value(strClientConfKey.ServerIP)),
int.Parse(ClientInfo.confMap.value(strClientConfKey.ServerPort)));
NetworkStream ns = client.GetStream();
IFormatter formatter = new BinaryFormatter();
formatter.Serialize(ns, sendPro);
reseivePro = (Protocol)formatter.Deserialize(ns);
client.Close();
}
else
{
return false;
}
return true;
}
catch (Exception)
{
return false;
}
}
示例11: LoadFromFile
public void LoadFromFile(string aPath)
{
using (Stream stream = File.Open(aPath, FileMode.Open))
{
Clear();
BinaryFormatter bin = new BinaryFormatter();
Configuration deserialized = bin.Deserialize(stream) as Configuration;
foreach (var prof in deserialized.Professors)
{
Professors.Add(prof);
}
foreach (var room in deserialized.Rooms)
{
Rooms.Add(room);
}
foreach (var group in deserialized.Groups)
{
Groups.Add(group);
}
foreach (var course in deserialized.Courses)
{
Courses.Add(course);
}
foreach (var constraint in deserialized.Constraints)
{
Constraints.Add(constraint);
}
foreach (var classcont in deserialized.Classes)
{
Classes.Add(classcont.Key, classcont.Value);
}
}
}
示例12: SetValue
private bool SetValue(object currentValue, out object newValue)
{
DTE dte = this.GetService<DTE>(true);
IDictionaryService dictionaryService = (IDictionaryService)ServiceHelper.GetService(this, typeof(IDictionaryService));
try
{
if (!string.IsNullOrEmpty(RecipeArgument))
{
string argumentvalue = dictionaryService.GetValue(RecipeArgument).ToString();
Version v = new Version(argumentvalue);
if (v != null)
{
byte[] bytes;
long length = 0;
MemoryStream ws = new MemoryStream();
BinaryFormatter sf = new BinaryFormatter();
sf.Serialize(ws, v);
length = ws.Length;
bytes = ws.GetBuffer();
newValue = Convert.ToBase64String(bytes, 0, bytes.Length, Base64FormattingOptions.None);
return true;
}
}
}
catch { }
//string projectId = currentProject.
newValue = "";
return false;
}
示例13: OnSaveData
public override void OnSaveData()
{
LoggerUtilities.Log("Saving road names");
BinaryFormatter binaryFormatter = new BinaryFormatter();
MemoryStream memoryStream = new MemoryStream();
try
{
RoadContainer[] roadNames = RoadNameManager.Instance().Save();
if (roadNames != null)
{
binaryFormatter.Serialize(memoryStream, roadNames);
serializableDataManager.SaveData(dataKey, memoryStream.ToArray());
LoggerUtilities.Log("Road names have been saved!");
}
else
{
LoggerUtilities.LogWarning("Couldn't save road names, as the array is null!");
}
}
catch (Exception ex)
{
LoggerUtilities.LogException(ex);
}
finally
{
memoryStream.Close();
}
}
示例14: Save
/// <summary>
/// Save the specified object.
/// </summary>
/// <param name="filename">The filename to save to.</param>
/// <param name="obj">The object to save.</param>
public static void Save(string filename, object obj)
{
Stream s = new FileStream(filename, FileMode.Create, FileAccess.Write, FileShare.None);
var b = new BinaryFormatter();
b.Serialize(s, obj);
s.Close();
}
示例15: Encode
/// <summary>
/// Encode value into a stream
/// </summary>
/// <param name="value">Value to encode</param>
/// <param name="destination">Stream to write the serialized object to.</param>
public void Encode(object value, Stream destination)
{
if (value == null) throw new ArgumentNullException("value");
if (destination == null) throw new ArgumentNullException("destination");
var formatter = new BinaryFormatter();
formatter.Serialize(destination, value);
}