5 Replies - 1908 Views - Last Post: 24 July 2011 - 04:16 PM Rate Topic: -----

#1 Reiyn  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 16
  • Joined: 15-February 08

serialization, writing and reading file

Posted 23 July 2011 - 11:48 PM

I have no errors, but my app does not create the file it should. It does not, in fact, seem to get through the Save method...
Any suggestions are appreciated; please do not write the code for me :)

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
using System.Runtime.Serialization;

namespace KjSProduct                       
{
    public partial class KjS : Form
    {
        protected string sPath = "";

        public KjS()
        {
            InitializeComponent();
            //Get user name
            String sUser = Environment.UserName;
            
            //execution check
            MessageBox.Show(sUser + ", Hello!");

            //set path for file storage to user's documents and settings folder
            sPath = "C:\\Documents and Settings\\" + sUser + "\\My Documents\\products.dat";
           
            //execution check
            MessageBox.Show("Your current directory is: " + sPath);
        }
        private void btnSave_Click(object sender, EventArgs e)
        {
            //get name from form
            string sName = txtName.Text;
            //execution check
            MessageBox.Show(sName);
            //create decimal price for later use
            decimal dPrice;

            try
            {
                //get price from the form, convert to decimal, on error set dPrice to 0
                dPrice = Convert.ToDecimal(txtPrice.Text);
                MessageBox.Show("dPrice is " + dPrice);
            }
            catch
            {
                dPrice = 0;
                throw;
            }
                //call save method
                Save(sName, dPrice);
        }
        
        private void Save(string sName, decimal dPrice)
        {
            //Create object to serialize
            Product products = new Product(sName, dPrice);

            //Create filestream object
            FileStream fs;
            fs = new FileStream("products.dat", FileMode.OpenOrCreate, FileAccess.Write);
            BinaryFormatter binformat = new BinaryFormatter();
            try
            {
                //Serialize
                binformat.Serialize(fs, products);
            }
            catch (SerializationException e)
            {
                MessageBox.Show("Serialization failed. Reason: " + e.Message);
            }
            
            finally
            {
            //Close filestream 
            fs.Close();
            MessageBox.Show("File saved");
            }
            }
        private void Read()
        {
            FileStream fs; // = null;

            try
            {
                //Create filestream object
                fs = new FileStream(sPath, FileMode.Open, FileAccess.Read);
                BinaryFormatter binFormat = new BinaryFormatter();

                //Clear list box 
                lstProducts.Items.Clear();
                //Deserialize previous object
                Product products = (Product)binFormat.Deserialize(fs);
                //Add items to list box
                lstProducts.Items.Add(products.getsName() + "  " + products.getdPrice());

                fs.Close();
            }
                //In case of error show file is unavailable
            catch
            {
                MessageBox.Show("That file is unavailable");
            }

        }
        private void btnRead_Click(object sender, EventArgs e)
        {
            //Call Read method
            Read();
        }
    }
}



I have a Product class for the gets n sets:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;

namespace KjSProduct
{
        [Serializable]
    //Class containing sName and dPrice, and gets and sets for them
        class Product
        {
            private string sName;
            private decimal dPrice;

            public Product(string sName, decimal dPrice)
            {
                this.sName = sName;
                this.dPrice = dPrice;
            }

            public void setsName(string sName)
            {
                this.sName = sName;
            }
            public string getsName()
            {
                return sName;
            }
            public void setdPrice(decimal dPrice)
            {
                this.dPrice = dPrice;
            }
            public decimal getdPrice()
            {
                return dPrice;
            }
    }
}



and of course main:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;

namespace KjSProduct
{
    static class Program
    {
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        [STAThread]
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new KjS());
            
        }
    }
}



I've looked at tutorials and tried several different examples of how to handle this, I am stumped.
Thanks for your assistance.
Kevin

Is This A Good Question/Topic? 0
  • +

Replies To: serialization, writing and reading file

#2 Curtis Rutland  Icon User is online

  • (╯□)╯︵ (~ .o.)~
  • member icon


Reputation: 4312
  • View blog
  • Posts: 7,467
  • Joined: 08-June 10

Re: serialization, writing and reading file

Posted 24 July 2011 - 12:14 AM

I don't know the problem, but I would be willing to guess that it's because you're using private fields and get/set methods. Try converting them to Properties and see if it serializes?

Properties work like this:

private string propName;

public string PropName{
  get{ return propName; }
  set { propName = value; }
}


It encapsulates a get/set method, and you can use it as if it were a field, without parenthesis (and you can directly assign to it). It's syntactic sugar over methods, but it works, and it's more semantic than the Java style of getter/setter methods, IMO. Even if this doesn't solve your problem, it's good to learn the C# way of doing things. It seems like you have a Java background, I'd guess.

This post has been edited by Curtis Rutland: 24 July 2011 - 12:14 AM

Was This Post Helpful? 1
  • +
  • -

#3 tlhIn`toq  Icon User is offline

  • Please show what you have already tried when asking a question.
  • member icon

Reputation: 5316
  • View blog
  • Posts: 11,361
  • Joined: 02-June 10

Re: serialization, writing and reading file

Posted 24 July 2011 - 03:04 AM

What do you mean by "It doesn't *appear* to get through the save method" ?

It either does, or it does not. This sounds like you're not sure and have not placed any breakpoints or done any actual debugging. Are you familiar with breakpoints? Do you know how to walk through the execution line by line and look at the variables' values as you do so?


See FAQ #5 for debugging tutorials
See FAQ #6 for Serialization and use of properties.




FAQ (Frequently Asked Questions - Updated July 2011

  • Q: My program doesn't work. I didn't show you any code or actually tell you the error message. How do I fix it?
    Spoiler


  • Q: How do I get Form 'A' to make a change or talk to Form 'B'


  • Q: I'm trying to make a password/login form and...
    A: Password handling tutorial


  • Q: I'm making a client/server chat program and .....
    A:Client/server chat tutorial


  • Q: I do x and y happens which I didn't expect but I don't know how to figure out why. How do I debug and find my problem?


  • Q: I don't understand XML Serialization so I can save my information/class


  • Q:How do I get sound in my program?
    A: Adding sound to your C# application


  • Q: How do I use the serial port?
    A: Serial port communication


  • Q: How do I deploy my program / Make an installer?
    A: C# application deployment project


  • Q: How do I do compression or .zip files?
    A:

  • Q: How do I do multi-threading? Having a problem with cross-threading...


  • Q: I am making a calculator as my school homework project and ...
    A: Calculator tutorial


  • Q: I've been struggling with this for days/weeks and I can't figure it out and my professor is worthless and can't teach. Can someone here explain it to me?
    Spoiler


  • Q: How do I save some information like preferences, settings or other data?


  • Q: I want my textbox to offer suggestions as the user types.
    A: Creating an auto-complete textbox


  • Q: I want to write a program that does x, y and z with features for A, B, and C. {Notice there is no question in this question}
    Spoiler


  • Q: I need to code to do x... Someone tell me the code for y...
    Spoiler


  • Q: What is the best programming language? What programming language should I learn?
    Spoiler


  • Q: How do I get my program to programmatically simulate a mouse click or button press?
    A: Simulate mouse and keystroke (even to another application)


  • Q: I'm not really sure what I want to do with my future? Do you guys like programming? I think I kinda like math and games and computers? What should I do or study?
    A: Get experience while you find yourself


[*]Q: How do I use PInvoke and the Win32 api calls to get functions not available in .NET framework?
A: Using the Win32 API Tutorial
Was This Post Helpful? 0
  • +
  • -

#4 Milto  Icon User is offline

  • D.I.C Head
  • member icon

Reputation: 23
  • View blog
  • Posts: 139
  • Joined: 10-February 11

Re: serialization, writing and reading file

Posted 24 July 2011 - 06:21 AM

I'm assuming it won't create the .xml save file when you want it to. I personally prefer a streamwriter when creating files. Set the name you want it to be set as followed by ".xml" to end the file name.
The good thing is streamwriters create the file in the .exe directory by default.

This post has been edited by Milto: 24 July 2011 - 06:22 AM

Was This Post Helpful? 0
  • +
  • -

#5 Curtis Rutland  Icon User is online

  • (╯□)╯︵ (~ .o.)~
  • member icon


Reputation: 4312
  • View blog
  • Posts: 7,467
  • Joined: 08-June 10

Re: serialization, writing and reading file

Posted 24 July 2011 - 09:37 AM

@Milto, notice that he's not using XML serialization, rather binary serialization.
Was This Post Helpful? 0
  • +
  • -

#6 Milto  Icon User is offline

  • D.I.C Head
  • member icon

Reputation: 23
  • View blog
  • Posts: 139
  • Joined: 10-February 11

Re: serialization, writing and reading file

Posted 24 July 2011 - 04:16 PM

Woops, my mistake. Immediately jumped to conclusions. :/
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1