Solved

Write Read Specific File

Posted on 2010-08-31
43
366 Views
Last Modified: 2013-12-17
Experts,

VS 2008 C# 3.5

I need to read and write a file in a specific format. What is the most effitient way to do it. I want to stick to a regular text file.

File Format would look something like this :
................Begin File................
Date: 8/31/2010
Type: XYZ
Parameter X : 12 13 14 12
Parameter Y:   65 43 10 65
Parameter Z:   25 25 25 25
.
.
.
...............End File..................

This is of course the simplified version of the file. What is the best way to read, write, update this file? What would the file handling class contain?

Should I look into Serialization?




0
Comment
Question by:San24
  • 20
  • 11
  • 6
  • +3
43 Comments
 

Expert Comment

by:asutorius
Comment Utility
What is the input file? Tab delimited?
0
 

Author Comment

by:San24
Comment Utility
It could be a tab delimited. Since I`m starting off I'm free to create a new format.
0
 
LVL 9

Expert Comment

by:puru1981
Comment Utility
like to know what is the purpose of writing the file?
0
 

Expert Comment

by:asutorius
Comment Utility
0
 

Author Comment

by:San24
Comment Utility
@puru1981 -
READ : The file will be the input parameters for a program that will do some calculations. Windows Forms.
WRITE : The user can also save the parameters, so that they can loaded in the program later.
0
 

Expert Comment

by:asutorius
Comment Utility
The other thing I was thinking about was something like this...
http://www.experts-exchange.com/Programming/Languages/C_Sharp/Q_24399133.html
0
 

Author Comment

by:San24
Comment Utility
@asutorius : I was thinking : I `ll have to read the file, use the regular expressions, then split the file and load the parameters. I was hoping there would a more effitient way to do this.

XML does make sense. Let me look into it.
0
 
LVL 9

Expert Comment

by:puru1981
Comment Utility
if it has to be read and written by programs only then i would like it to be a binary file so that no one can change it.

you can write your custom formatter to format the file and again read it.
0
 

Author Comment

by:San24
Comment Utility
@puru - Could you link me to an example?
0
 
LVL 9

Expert Comment

by:puru1981
Comment Utility
0
 
LVL 9

Expert Comment

by:puru1981
Comment Utility
0
 

Author Comment

by:San24
Comment Utility
I`m lost!

Can anyone guide me regarding how to go about making a custom binary formatter for a file. I think I`m frustrated to the point where I need some code snippets, starting point.

Date: 8/31/2010
Type: XYZ
Parameter X : 12 13 14 12
Parameter Y:   65 43 10 65
Parameter Z:   25 25 25 25
.
.
.
...............End File..................
0
 
LVL 85

Expert Comment

by:Mike Tomlinson
Comment Utility
I would go the XML route...

First create a CLASS or classes that holds the information and then it will be really easy.

Does the date entry only appear at the top of the file or is it duplicated for each "record"?

Show some more sample data with more than one record (if that applies) and we can help you develop the code...
0
 

Author Comment

by:San24
Comment Utility
@Idle Mind - There are no more records. This would be a parameter file for a program.  

Attached are samples of two different files.
File Type XYZ : This would have XYZ as the file extension

Date: 8/31/2010
Type: XYZ
Parameter X : 12 13 14 12
Parameter Y:   65 43 10 65
Parameter Z:   25 25 25 25

File Type ABC : This would have ABC as the file extension

Date: 8/31/2010
Type: ABC
Parameter A : 12 13 14 12 12 12 13 15
Parameter B:   65 43 10 65
Parameter C:   25 25 25 25 14 13 13
0
 
LVL 85

Expert Comment

by:Mike Tomlinson
Comment Utility
Is it always just three parameters?

The number of values after each parameter is variable then?
0
 

Author Comment

by:San24
Comment Utility
Yes .. The number of parameters are variable, so are the values. But for a particular file type they are fixed. The number of paramters between two file types are different.

File Type XYZ - 3 Parameters , But the parameters can have no values. In that case I would want some default values.

Parameter X : 12 13 14 12
Parameter Y:   65 43 10 65
Parameter Z:   null null null null

Then Z would get some default values of 12 13 14 15
0
 
LVL 8

Expert Comment

by:Gururaj Badam
Comment Utility
[Section]
Date=8/31/2010
Type=XYZ
Parameter X=12 13 14 12
Parameter Y=65 43 10 65
Parameter Z=25 25 25 25

If you are fine with above format, you can Read using ReadPrivateProfileString and for Writing use WritePrivateProfileString Win32 APIs

http://msdn.microsoft.com/en-us/library/ms725501(VS.85).aspx

http://msdn.microsoft.com/en-us/library/ms724353(v=VS.85).aspx

Google it and you will find enormous code sample. Otherwise I can forward.
0
 

Author Comment

by:San24
Comment Utility
How about I use Serialization?

Write :
 FileStream flStream = new FileStream(@"C:\Test\abc.dat",FileMode.OpenOrCreate, FileAccess.Write);
            try
            {
                BinaryFormatter binFormatter = new BinaryFormatter();
                binFormatter.Serialize(flStream, myObj);
            }
            finally
            {
                flStream.Close();
            }

Read:
 FileStream flStream = new FileStream(@"C:\Test\abc.dat",FileMode.OpenOrCreate, FileAccess.Write);
            try
            {
                BinaryFormatter binFormatter = new BinaryFormatter();
                readStore = (Store)binFormatter.Deserialize(flStream);

                Console.WriteLine(">>>" + MyObj.Param1+ "<<<<");
            }
            finally
            {
                flStream.Close();
            }

Any drawbacks to this way of doing it?
0
 
LVL 8

Expert Comment

by:Gururaj Badam
Comment Utility
There's no harm, may be i missed the fact that you wanted to convert back into objects.
0
 

Author Comment

by:San24
Comment Utility
Yeah, I`m sorry if  I forgot to mention that. Basically - write the parameters and then read the parameters to the program.
0
 
LVL 9

Assisted Solution

by:puru1981
puru1981 earned 250 total points
Comment Utility
i have suggested the same but. i have just given you a way to make your formatter customized.
0
What Is Threat Intelligence?

Threat intelligence is often discussed, but rarely understood. Starting with a precise definition, along with clear business goals, is essential.

 

Author Comment

by:San24
Comment Utility
Thanks puru1981..I just got confused with the example. But going back to the link you sent me, makes it more understandable now.
0
 
LVL 1

Expert Comment

by:JensMig
Comment Utility
You should definately go the XML way. Its much easier to manipulate than a text file. If you do not want users to edit the file, than just save it in another format on the disk, like hexadecimal or encrypt it in some way (which is more secure).

Your XML could be structured like this:

<Configuration>

  <Type>ABC</Type>

  <Parameters>

    <Parameter Name="A">

      <Values>

        <Value>12</Value>

        <Value>13</Value>

        <Value>14</Value>

      </Values>

    </Parameter>

  </Parameters>

</Configuration>

Open in new window

0
 
LVL 85

Expert Comment

by:Mike Tomlinson
Comment Utility
Can you show us the class declaration for "myObj" in your post back here?
http://www.experts-exchange.com/Programming/Languages/C_Sharp/Q_26441160.html#33569773
0
 

Author Comment

by:San24
Comment Utility
Here is the Class. Its a UserCntrl.

Also, I`m trying to do Serialization and am getting a Runtime Type type, Stream Context context, etc errors. It worked in the example above.

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Collections;

namespace McCAWind
{
    [Serializable]
    public partial class CicalUserCntrl : UserControl,Form1.CixUserInterface
    {
        CicalParamUserCntrl HUC = new CicalParamUserCntrl();

        public CicalUserCntrl()
        {
            InitializeComponent();
            Dock = DockStyle.Fill;
           
            this.Controls.Add(HUC);
        }

        #region CixUserInterface Members

        CicalUserCntrl Form1.CixUserInterface.GetHUserCntrl()
        {
            return this;
        }

        #endregion

        public double HUCParamOne
        {
            get
            {
                return HUC.HParamOne;
            }
            set
            {
                HUC.HParamOne = value;
            }
        }

        public double HUCParamTwo
        {
            get
            {
                return HUC.HParamTwo;
            }
            set
            {
                HUC.HParamTwo = value;
            }
        }

        public double HUCParamThree
        {
            get
            {
                return HUC.HParamThree;
            }
            set
            {
                HUC.HParamThree = value;
            }
        }

        public double HUCParamFour
        {
            get
            {
                return HUC.HParamFour;
            }
            set
            {
                HUC.HParamFour = value;
            }
        }

    }
}
0
 
LVL 85

Expert Comment

by:Mike Tomlinson
Comment Utility
It's a real pain in the butt to serialize controls...

You'd be better off just writing a separate "helper" class that holds just the data that needs to be saved, copying the data over, and then serializing that class with XML.
0
 

Author Comment

by:San24
Comment Utility
ooh damn! How would the helper class look like? The problem I`m dealing with is there are layers of User Controls, and communication between them is just being a real pain.
0
 
LVL 85

Expert Comment

by:Mike Tomlinson
Comment Utility
...it would just be a custom class, that inherits from nothing, and has your data fields in it.

An overly simplified example:

    [Serializable]
    public partial class Data
    {
        public Data() {}

        public string A;
        public string B;
        public string C;
    }
0
 

Author Comment

by:San24
Comment Utility
I`m having decent luck with the new helper class approach. But this might be a silly question but...How would the helper class get the vlaues from the User Control?

  [Serializable]
    public partial class Data
    {
        public Data() {}

        public string A; //User Control Value?
        public string B;  //User Control Value?
        public string C;  //User Controll Value?
    }

0
 
LVL 85

Expert Comment

by:Mike Tomlinson
Comment Utility
You either MANUALLY populate them...

...or give your helper class a Constructor() that receives your UserControl and pulls the data from it.
*This is just manually populating the helper class but from WITHIN the class itself.

public partial class Data
{

    public Data() {}

    public Data(CicalUserCntrl cuc)
    {
        // made up example...
        this.A = cuc.A;
        this.B = cuc.B;
        this.C = cuc.C;
    }

}
0
 

Author Comment

by:San24
Comment Utility
So,
I made up a small example :
UserControl.cs - This consists of only a single textbox
 public partial class UserControl1 : UserControl
    {
        public UserControl1()
        {
            InitializeComponent();
        }
    }

    [Serializable]
    public partial class HelperClass
    {
        public string  startPos;

        public HelperClass(UserControl1 UC)
        {
            this.startPos = UC.textBox1.Text;
        }
    }

Form1.cs
 private void button1_Click(object sender, EventArgs e)
        {
            //I know this is wrong
            UserControl1 UC1 = new UserControl1();
            panel1.Controls.Add(UC1);
            HelperClass HC = new HelperClass(UC1);

            FileStream flStream = new FileStream(@"C:\Custom\FileTest.txt",FileMode.OpenOrCreate, FileAccess.Write);

            try
            {
                BinaryFormatter binFormatter = new BinaryFormatter();
                binFormatter.Serialize(flStream, HC);
                Console.WriteLine("...." + HC.startPos + "....");
            }
            catch(Exception Ex)
            {
                MessageBox.Show(Ex.StackTrace.ToString());
            }
            finally
            {
                flStream.Close();
            }
        }

How do I pass the reference back to the main form?
0
 
LVL 85

Expert Comment

by:Mike Tomlinson
Comment Utility
"How do I pass the reference back to the main form?"

The reference to WHAT back to the main form?  Does your sample work?
0
 

Author Comment

by:San24
Comment Utility
Idle_Mind - No the sample doesn`t work.

On the main form, I have this. But all this is doing is creating a new instance of the UserControl1
           UserControl1 UC1 = new UserControl1();
            panel1.Controls.Add(UC1);
            HelperClass HC = new HelperClass(UC1);

I was wondering how do i pass the reference of the UserControl1 instance on to the main form.

I want to access the values [startpos] in UserControl1 on the main form.

0
 
LVL 85

Expert Comment

by:Mike Tomlinson
Comment Utility
...have you tried passing in the name of your UserControl1 from your main form?

    // UserControl1 UC1 = new UserControl1();
    // panel1.Controls.Add(UC1);

    HelperClass HC = new HelperClass(this.NameOfUserControl1OnForm1Here);
0
 
LVL 9

Expert Comment

by:puru1981
Comment Utility
you can use it like HC.startpos since it is a public member.
0
 

Author Comment

by:San24
Comment Utility
UserControl1

public class HelperClass
{
      public string ValOne
          {
                get
                          {
                            //Value of one of the controls in UserControl1
                            }
                 set
                           {
                         
                            }
       }
}

Whats the right way for HelperClass to get values of the controls in UserControl1?






}
0
 
LVL 85

Expert Comment

by:Mike Tomlinson
Comment Utility
You either need to:
(1) Expose Custom Public Properties in UserControl1 that simply wrap the control values in question.
(2) Make the Modifiers() property of the controls in UserControl1 Public so they can be accessed from outside the control.
0
 

Author Comment

by:San24
Comment Utility
Idle Mind - I`ve tried both the approaches. Can you give me an example.
0
 
LVL 85

Expert Comment

by:Mike Tomlinson
Comment Utility
Ok...so you'd store the reference to the passed in UserControl1 in your HelperClass:

    public class HelperClass
    {

        private UserControl1 uc1;

        public HelperClass(UserControl1 uc1)
        {
            this.uc1 = uc1;
        }

    }

Now you can use "uc1" in your properties:

          public string ValOne
          {
              get
              {
                  return this.uc1.SomeControl.SomeValue;
              }
              set
              {
                         
              }
       }

*Remember, to be able to access "SomeControl" in UserControl1, its Modifiers() property needs to be set to Public.
0
 

Author Comment

by:San24
Comment Utility
I`m getting a System.NullReferenceException.

Here is the code so far. I`m trying to serialize / deserialize the helper class:

UserCntrl  > HelParam
................
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace TestXYZ
{
    [Serializable]
    public partial class HelParam : UserControl
    {
        public HelParam()
        {
            InitializeComponent();
        }

        public string TStr
        {
            get
            {
                return textBox1.Text;
            }
            set
            {
                textBox1.Text = value;
            }
        }
    }

    [Serializable]
    public class HelperClass
    {
        [NonSerialized]
        private HelParam hC;

        public HelperClass(HelParam HC)
        {
            this.hC = HC;
        }

        //I "cannot" serialize/deserialize this
        public String Str1
        {
            get
            {
                return hC.TStr;
            }
            set
            {
                hC.TStr = value;
            }
        }

        //I can serialize/deserialize this
        private string str2 = "Random";
        public String Str2
        {
            get
            {
                return str2 ;
            }
            set
            {
                str2 = value;
            }
        }
    }
}

.................................
On the Main form

Serialization
....................
  private void button2_Click(object sender, EventArgs e)
        {
            //int i = Convert.ToInt32(textBox1.Text);
            int i = 0;

            String FileName = @"FileNameHere";
            FileStream FileStream = new FileStream(FileName, FileMode.OpenOrCreate, FileAccess.Write);

            HelParam HPW = new HelParam();
            HPW = HelList[i];                                //HelList is a list of HelParam UserCntrl Objects

            HelperClass HCWrite = new HelperClass(HPW);
            Console.WriteLine("This Works : " + HCWrite.Str1);

            try
            {
                BinaryFormatter BinFormatter = new BinaryFormatter();
                BinFormatter.Serialize(FileStream, HCWrite);
                Console.WriteLine("Serialization Complete");
            }
            finally
            {
                FileStream.Close();
            }
        }


Deserialize
..................
  private void button3_Click(object sender, EventArgs e)
        {
            //int i = Convert.ToInt32(textBox1.Text);
            int i = 0;

            String FileName = @"FileNameHere";
            FileStream flStream = new FileStream(FileName, FileMode.Open, FileAccess.Read);

            HelParam HPR = new HelParam();
            HPR = HelList[i];                                    //HelList is a list of HelParam UserCntrl Objects

            HelperClass HCRead = new HelperClass(HPR);

            try
            {
                BinaryFormatter binFormatter = new BinaryFormatter();
                HCRead = (HelperClass)binFormatter.Deserialize(flStream);
                Console.WriteLine(">>> Deserialized : " + HCRead.Str1 + " " + HCRead.Str2 + "<<<");
            }
            finally
            {
                flStream.Close();
            }
        }

Not sure where I`m going wrong. In Serialization or Deserialization?
0
 
LVL 85

Accepted Solution

by:
Mike Tomlinson earned 250 total points
Comment Utility
...well...AFTER deserialization the "hC" variable will be NULL since it is non-serialized and therefore you can't retrieve anything from it in the  "Str1" property.  

So I guess really you should create a variable to hold the value of "hC.TStr" and serialize that instead.
0
 

Author Comment

by:San24
Comment Utility
I think I figured it out, slightly different approach. Let me post the updated code tomorrow, might help others.
0
 

Author Closing Comment

by:San24
Comment Utility
Solution Reached.
0

Featured Post

How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

Join & Write a Comment

In my previous article (http://www.experts-exchange.com/Programming/Languages/.NET/.NET_Framework_3.x/A_4362-Serialization-in-NET-1.html) we saw the basics of serialization and how types/objects can be serialized to Binary format. In this blog we wi…
A long time ago (May 2011), I have written an article showing you how to create a DLL using Visual Studio 2005 to be hosted in SQL Server 2005. That was valid at that time and it is still valid if you are still using these versions. You can still re…
This video gives you a great overview about bandwidth monitoring with SNMP and WMI with our network monitoring solution PRTG Network Monitor (https://www.paessler.com/prtg). If you're looking for how to monitor bandwidth using netflow or packet s…
Polish reports in Access so they look terrific. Take yourself to another level. Equations, Back Color, Alternate Back Color. Write easy VBA Code. Tighten space to use less pages. Launch report from a menu, considering criteria only when it is filled…

762 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

6 Experts available now in Live!

Get 1:1 Help Now