Click here to Skip to main content
15,900,725 members
Please Sign up or sign in to vote.
3.50/5 (2 votes)
Hi,
I create a application in which I need to stored and read the string array in a Binary file and also others data type in the same binary file.
My Data Fields are :-
C#
string[] Days;
string msg;
DateTime time;
String FilePath;


How do I save(write) and read all above data Fields value in one binary file???

Thanks In Advanced!!!

With Regards
Jayanta..
Posted

C#
using System.Runtime.Serialization.Formatters.Binary;
using System.IO;

C#
private void Test()
{
    string file = "C:\\file";
    object ob1 = GetSomeObject();
    byte[] ba = ConvertObjectToByteArray(ob1);
    File.WriteAllBytes(file, ba);

    byte[] ba2 = File.ReadAllBytes(file);
    object ob2 = ConvertByteArrayToObject(ba);
}

C#
public static byte[] ConvertObjectToByteArray(object ob)
{
    BinaryFormatter bf = new BinaryFormatter();
    MemoryStream ms = new MemoryStream();
    bf.Serialize(ms, ob);
    return ms.ToArray();
}

public static object ConvertByteArrayToObject(byte[] ba)
{
    BinaryFormatter bf = new BinaryFormatter();
    Stream stream = new MemoryStream(ba);
    return bf.Deserialize(stream);
}

Update
Write string as binary file:
C#
string file = "C:\\file";
string string1 = "John|Gold Membership|RegisterDate=2013-12-13";
byte[] ba = Encoding.UTF8.GetBytes(string1);
File.WriteAllBytes(file,ba);

byte[] ba2 = File.ReadAllBytes(file);
string string2 = Encoding.UTF8.GetString(ba2);

MessageBox.Show(string2);
 
Share this answer
 
v2
Comments
adriancs 13-Dec-13 3:38am    
I have updated my answer for writing string as binary file.
You can do it with BinaryFormatter class. Ya, there are many solutions fit to you question but more sophisticated serializing you can do it. See below.
BinaryFormatter vs. Manual Serializing[^]
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900