On 3 Apr, 16:00, "Nicholas Paldino [.NET/C# MVP]"
<m...@spam.guard.caspershouse.comwrote:
Glenn,
Why not just use a binary formatter and serialization? Or do you have a
requirement to read files that were already persisted from another
application with a custom format?
--
- Nicholas Paldino [.NET/C# MVP]
- m...@spam.guard.caspershouse.com
"Glenn" <bagsm...@frontiernet.netwrote in message
news:bo********************************@4ax.com...
OK, need help in translating what I'd like to do in old school C to
best method C#
If I was wanting to create an array of struct's, writing and reading
them to/from a file.. how would I do this in C#?
I was thinking, in so far as in memory, it would be a list of the
struct..?
For writing to file though, if I do a write of the struct, it's not
working correctly. Should I be using something other than StreamWriter
here?
Thanks for any help :)
Glenn- Hide quoted text -
- Show quoted text -
I get quite confused by the variety of writers/readers/streams and
formatters. Here's a tiny example which will do what you want, but a)
it's 1.1 code and b) I'm not sure it's using the most appropriate bits
of the framework. Watch for line wrap, I fully qualified everything
while I hunted through the framework looking for the relevant bits.
All the ISerializable stuff on the struct is entirely optional.
using System;
using System.Xml.Serialization;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters;
using System.IO;
namespace WindowsApplication13
{
[Serializable]
struct AStruct : ISerializable
{
public AStruct(int px, string ps)
{
x=px;
s=ps;
}
public AStruct(SerializationInfo information, StreamingContext
context)
{
x=(int)information.GetValue("x",typeof(int));
s=information.GetString("s");
}
public int x;
public string s;
#region ISerializable Members
public void GetObjectData(SerializationInfo info, StreamingContext
context)
{
info.AddValue("x",x);
info.AddValue("s",s);
}
#endregion
}
public class Class2
{
public Class2()
{}
public void WriteToFile()
{
System.Runtime.Serialization.Formatters.Binary.Bin aryFormatter bf =
new System.Runtime.Serialization.Formatters.Binary.Bin aryFormatter();
System.Collections.ArrayList al = new
System.Collections.ArrayList();
al.Add(new AStruct(1,"test1"));
al.Add(new AStruct(2,"test2"));
al.Add(new AStruct(3,"test3"));
al.Add(new AStruct(4,"test4"));
using(System.IO.FileStream fs = new FileStream(@"C:
\out.bin",System.IO.FileMode.Create))
{
bf.Serialize(fs,al);
fs.Close();
}
}
public void ReadFromFile()
{
System.Runtime.Serialization.Formatters.Binary.Bin aryFormatter bf =
new System.Runtime.Serialization.Formatters.Binary.Bin aryFormatter();
System.Collections.ArrayList al = new
System.Collections.ArrayList();
using(System.IO.FileStream fs = new FileStream(@"C:
\out.bin",System.IO.FileMode.Open))
{
System.IO.BinaryReader br = new BinaryReader(fs);
al = (System.Collections.ArrayList)bf.Deserialize(fs);
fs.Close();
}
Console.WriteLine(al.Count);
}
}
}