Quantcast
Channel: CodeProject Latest postings for ASP.NET
Viewing all articles
Browse latest Browse all 3938

Writing multiple records to a binary file, reading the file records so I can add a record and write

$
0
0
This is for a website that I'm building for my neighbor, and for future builds.
I don't want to use a database in this project, or XML unless I have to.
I thought I might be able to get away with using a binary file with multiple records to store contact us info.

So I have 1 record written so far. I'm trying to read the whole file and just add a record to it.
When I loop through the records, I get an error;
Unable to cast object of type 'System.Collections.Generic.List`1[genericMVC.Models.serialized_contactUs]' to type 'genericMVC.Models.serialized_contactUs'.

I thought I had casted it correctly, but this is the first test of the code, having to fix the issue of opening the file first.
The model is a typical model like in MVC, only I added serialized to the top of the class.
I haven't tried anything yet because I'm not sure if I'm on the right track here; or if my thought is even close to being possible.
 
string folderPath = HostingEnvironment.MapPath("~/App_Data/Database");if (Directory.Exists(folderPath) == false)
    Directory.CreateDirectory(folderPath); string binaryPath = folderPath += "\\contactUs_messages.bin";if (File.Exists(binaryPath))
{using (var fs = new FileStream(binaryPath, FileMode.Open))
    {if (fs != null)
        {// Read all the records and enter them into a generic collection
            List<serialized_contactUs> data = new List<serialized_contactUs>();var bf = new BinaryFormatter();while (fs.Position < fs.Length)
            {
                serialized_contactUs contact = (serialized_contactUs)bf.Deserialize(fs);
                data.Add(new serialized_contactUs()
                {
                    Name = contact.Name,
                    CompanyName = contact.CompanyName,
                    EmailAddress = contact.EmailAddress,
                    Phone_Number = contact.Phone_Number,
                    Phone_Ext = contact.Phone_Ext,
                    Phone_Mobile = contact.Phone_Mobile,
                    MessageContent = contact.MessageContent,
                    Time_Stamp = contact.Time_Stamp,
                    Time_Zone = contact.Time_Zone,
                    RememberMe = contact.RememberMe,
                    MailingList = contact.MailingList
                });
            }
            bf.Serialize(fs, data);
        }
 
If it ain't broke don't fix it

Viewing all articles
Browse latest Browse all 3938

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>