本文整理汇总了C#中System.Runtime.Serialization.Formatters.Binary.BinaryFormatter.Serialize方法的典型用法代码示例。如果您正苦于以下问题:C# System.Runtime.Serialization.Formatters.Binary.BinaryFormatter.Serialize方法的具体用法?C# System.Runtime.Serialization.Formatters.Binary.BinaryFormatter.Serialize怎么用?C# System.Runtime.Serialization.Formatters.Binary.BinaryFormatter.Serialize使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
的用法示例。
在下文中一共展示了System.Runtime.Serialization.Formatters.Binary.BinaryFormatter.Serialize方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: SaveFile
public static void SaveFile()
{
try
{
System.IO.FileStream stream = new System.IO.FileStream("\\lastfiles.dat", System.IO.FileMode.Create);
System.Runtime.Serialization.Formatters.Binary.BinaryFormatter formatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
formatter.Serialize( stream, recentProjects );
formatter.Serialize( stream, recentFiles );
stream.Flush();
stream.Close();
}
catch{}
}
示例2: Save
/// <summary>
/// Sauvegarde tous les joueurs.
/// </summary>
/// <param name="joueurs">La liste de joueurs a sauvegarder</param>
public static void Save(List<Joueur> joueurs)
{
try
{
using (Stream stream = File.Open(PATH_TO_DAT_FILE, FileMode.Create))
{
var bformatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
if (joueurs.Any())
{
bformatter.Serialize(stream, joueurs);
}
}
}
catch (ArgumentException)
{
MessageBox.Show("Le fichier est invalide.");
}
catch (DirectoryNotFoundException)
{
MessageBox.Show("Répertoire introuvable");
}
catch (FileNotFoundException)
{
MessageBox.Show("Le fichier n'existe pas.");
}
catch (IOException)
{
MessageBox.Show("Problème lors de la lecture du fichier.");
}
catch (System.Runtime.Serialization.SerializationException e)
{
MessageBox.Show(e.Message);
}
}
示例3: TestSerializeSchemaPropertyValueCollection
public void TestSerializeSchemaPropertyValueCollection()
{
System.Runtime.Serialization.Formatters.Binary.BinaryFormatter bf = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
System.IO.MemoryStream ms = new System.IO.MemoryStream();
SchemaPropertyValueCollection obj1 = new SchemaPropertyValueCollection();
SCGroup group = SCObjectGenerator.PrepareGroupObject();
foreach (string key in group.Properties.GetAllKeys())
{
obj1.Add(group.Properties[key]);
}
bf.Serialize(ms, obj1);
ms.Seek(0, System.IO.SeekOrigin.Begin);
var obj2 = (SchemaPropertyValueCollection)bf.Deserialize(ms);
Assert.AreEqual(obj1.Count, obj2.Count);
var keys1 = obj1.GetAllKeys();
foreach (var key in keys1)
{
Assert.IsTrue(obj2.ContainsKey(key));
Assert.AreEqual(obj1[key].StringValue, obj2[key].StringValue);
}
}
示例4: Save
// Pelaajien tallennus tiedostoon
public void Save(string filepath, List<Pelaaja> players)
{
// Haetaan tiedostopääte
string ext = Path.GetExtension(filepath);
// käynnistetään stream
using (Stream stream = File.Open(filepath, FileMode.Create))
{
// tarkastetaan tiedostopäätteen perusteella
// missä muodossa se halutaan tallentaa
switch (ext)
{
case ".xml":
XmlSerializer xmlSerializer = new XmlSerializer(typeof(List<Pelaaja>));
xmlSerializer.Serialize(stream, players);
break;
case ".bin":
var bformatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
bformatter.Serialize(stream, players);
break;
default:
throw new Exception("Extension \"" + ext + "\" is not supported");
}
}
}
示例5: SerializeBin
public static bool SerializeBin(string filePath, object target)
{
if (target == null)
{
return false;
}
if (string.IsNullOrEmpty(filePath))
{
return false;
}
try
{
System.Runtime.Serialization.Formatters.Binary.BinaryFormatter formatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
System.IO.Stream stream = new System.IO.FileStream(filePath, System.IO.FileMode.OpenOrCreate);
formatter.Serialize(stream, target);
stream.Close();
return true;
}
catch
{
return false;
}
}
示例6: Fetch
/// <summary>
/// Get an existing business object.
/// </summary>
/// <param name="request">The request parameter object.</param>
public byte[] Fetch(byte[] req)
{
var formatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
Csla.Server.Hosts.WcfBfChannel.FetchRequest request;
using (var buffer = new System.IO.MemoryStream(req))
{
request = (Csla.Server.Hosts.WcfBfChannel.FetchRequest)formatter.Deserialize(buffer);
}
Csla.Server.DataPortal portal = new Csla.Server.DataPortal();
object result;
try
{
result = portal.Fetch(request.ObjectType, request.Criteria, request.Context);
}
catch (Exception ex)
{
result = ex;
}
var response = new WcfResponse(result);
using (var buffer = new System.IO.MemoryStream())
{
formatter.Serialize(buffer, response);
return buffer.ToArray();
}
}
示例7: GetStock
public Stock GetStock(StockName stockName, DateTime startDate, DateTime endDate)
{
string dir = String.Format(@"..\..\StockData\Yahoo");
string filename = String.Format("{0}.stock", stockName);
var fullPath = Path.Combine(dir, filename);
List<IStockEntry> rates;
if (!File.Exists(fullPath))
{
rates = GetStockFromRemote(stockName, startDate, endDate);
Directory.CreateDirectory(dir);
using (Stream stream = File.Open(fullPath, FileMode.Create))
{
var bformatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
bformatter.Serialize(stream, rates);
}
}
else
{
using (Stream stream = File.Open(fullPath, FileMode.Open))
{
var bformatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
rates = (List<IStockEntry>) bformatter.Deserialize(stream);
}
}
var stock = new Stock(stockName, rates);
return stock;
}
示例8: Compress
public static byte[] Compress(System.Runtime.Serialization.ISerializable obj)
{
// infile.Length];
IFormatter formatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
MemoryStream ms = new MemoryStream();
formatter.Serialize(ms, obj);
byte[] buffer = ms.ToArray();
//Stream stream = new MemoryStream();
// FileStream("MyFile.bin", FileMode.Open, FileAccess.Read, FileShare.Read);
//MyObject obj = (MyObject)formatter.Deserialize(stream);
//stream.Close();
// Use the newly created memory stream for the compressed data.
MemoryStream msOutput = new MemoryStream();
GZipStream compressedzipStream = new GZipStream(msOutput, CompressionMode.Compress, true);
compressedzipStream.Write(buffer, 0, buffer.Length);
// Close the stream.
compressedzipStream.Close();
return msOutput.ToArray();
}
示例9: TestBulkDeletionResultsSerializable
public void TestBulkDeletionResultsSerializable()
{
var successfulObjects = new[] { "/container/object1", "/container/object2" };
var failedObjects =
new[]
{
new BulkDeletionFailedObject("/badContainer/object3", new Status((int)HttpStatusCode.BadRequest, "invalidContainer")),
new BulkDeletionFailedObject("/container/badObject", new Status((int)HttpStatusCode.BadRequest, "invalidName"))
};
BulkDeletionResults results = new BulkDeletionResults(successfulObjects, failedObjects);
BinaryFormatter formatter = new BinaryFormatter();
using (Stream stream = new MemoryStream())
{
formatter.Serialize(stream, results);
stream.Position = 0;
BulkDeletionResults deserialized = (BulkDeletionResults)formatter.Deserialize(stream);
Assert.IsNotNull(deserialized);
Assert.IsNotNull(deserialized.SuccessfulObjects);
Assert.AreEqual(successfulObjects.Length, deserialized.SuccessfulObjects.Count());
for (int i = 0; i < successfulObjects.Length; i++)
Assert.AreEqual(successfulObjects[i], deserialized.SuccessfulObjects.ElementAt(i));
Assert.IsNotNull(deserialized.FailedObjects);
Assert.AreEqual(failedObjects.Length, deserialized.FailedObjects.Count());
for (int i = 0; i < failedObjects.Length; i++)
{
Assert.IsNotNull(deserialized.FailedObjects.ElementAt(i));
Assert.AreEqual(failedObjects[i].Object, deserialized.FailedObjects.ElementAt(i).Object);
Assert.IsNotNull(deserialized.FailedObjects.ElementAt(i).Status);
Assert.AreEqual(failedObjects[i].Status.Code, deserialized.FailedObjects.ElementAt(i).Status.Code);
Assert.AreEqual(failedObjects[i].Status.Description, deserialized.FailedObjects.ElementAt(i).Status.Description);
}
}
}
示例10: Write
public void Write(string key, LocationCacheRecord lcr)
{
System.Runtime.Serialization.Formatters.Binary.BinaryFormatter formatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
System.IO.MemoryStream ms = new System.IO.MemoryStream();
formatter.Serialize(ms, lcr);
cache.Write(key, ms.ToArray(), true);
}
示例11: SerializeBinary
/// <summary>
/// 序列化为二进制字节数组
/// </summary>
/// <param name="request">要序列化的对象 </param>
/// <returns>字节数组 </returns>
public static byte[] SerializeBinary(object request)
{
System.Runtime.Serialization.Formatters.Binary.BinaryFormatter serializer = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
System.IO.MemoryStream memStream = new System.IO.MemoryStream();
serializer.Serialize(memStream, request);
return memStream.GetBuffer();
}
示例12: RecreateBinFiles
public void RecreateBinFiles()
{
DataTable testOutput;
using (
var connection =
new SqlConnection("Server=localhost;Database=AdventureWorks2012;Trusted_Connection=True;"))
{
var qryText = new StringBuilder();
qryText.AppendLine(QRY);
testOutput = new DataTable();
using (var command = connection.CreateCommand())
{
command.Connection.Open();
command.CommandType = CommandType.Text;
command.CommandText = qryText.ToString();
using (var da = new SqlDataAdapter { SelectCommand = command })
da.Fill(testOutput);
command.Connection.Close();
}
}
var binSer = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
using (var ms = new MemoryStream())
{
binSer.Serialize(ms, testOutput);
using (var binWtr = new BinaryWriter(File.Open(@"C:\Projects\31g\trunk\Code\NoFuture.Tests\Sql\DataTable.Person.bin", FileMode.Create)))
binWtr.Write(ms.GetBuffer());
}
}
示例13: TestBooleanQuerySerialization
public void TestBooleanQuerySerialization()
{
Lucene.Net.Search.BooleanQuery lucQuery = new Lucene.Net.Search.BooleanQuery();
lucQuery.Add(new Lucene.Net.Search.TermQuery(new Lucene.Net.Index.Term("field", "x")), Occur.MUST);
System.Runtime.Serialization.Formatters.Binary.BinaryFormatter bf = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
System.IO.MemoryStream ms = new System.IO.MemoryStream();
bf.Serialize(ms, lucQuery);
ms.Seek(0, System.IO.SeekOrigin.Begin);
Lucene.Net.Search.BooleanQuery lucQuery2 = (Lucene.Net.Search.BooleanQuery)bf.Deserialize(ms);
ms.Close();
Assert.AreEqual(lucQuery, lucQuery2, "Error in serialization");
Lucene.Net.Search.IndexSearcher searcher = new Lucene.Net.Search.IndexSearcher(dir, true);
int hitCount = searcher.Search(lucQuery, 20).TotalHits;
searcher.Close();
searcher = new Lucene.Net.Search.IndexSearcher(dir, true);
int hitCount2 = searcher.Search(lucQuery2, 20).TotalHits;
Assert.AreEqual(hitCount, hitCount2, "Error in serialization - different hit counts");
}
示例14: BinaryStreamFromObject
/// <summary>
/// Uses the System formatters to save the MapXtreme objects in the session state as a binary blob.
/// </summary>
/// <param name="ser">A serializable object.</param>
/// <remarks>If you simply send it to the Session state it will automatically extract itself the next time the user accesses the site. This allows you to deserialize certain objects when you want them. This method takes an object and saves it's binary stream.</remarks>
/// <returns>A byte array to hold binary format version of object you passed in.</returns>
public static byte[] BinaryStreamFromObject(object ser)
{
System.IO.MemoryStream memStr = new System.IO.MemoryStream();
System.Runtime.Serialization.Formatters.Binary.BinaryFormatter formatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
formatter.Serialize(memStr, ser);
return memStr.GetBuffer();
}
示例15: ObjectToByteArray
/// <summary>
/// 扩展方法:将对象序列化为二进制byte[]数组-通过系统提供的二进制流来完成序列化
/// </summary>
/// <param name="Obj">待序列化的对象</param>
/// <param name="ThrowException">是否抛出异常</param>
/// <returns>返回结果</returns>
public static byte[] ObjectToByteArray(this object Obj, bool ThrowException)
{
if (Obj == null)
{
return null;
}
else
{
try
{
System.Runtime.Serialization.Formatters.Binary.BinaryFormatter formatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
System.IO.MemoryStream stream = new System.IO.MemoryStream();
formatter.Serialize(stream, Obj);
return stream.ToArray();
}
catch (System.Exception ex)
{
if (ThrowException)
{
throw ex;
}
else
{
return null;
}
}
}
}