Results 1 to 12 of 12
  1. #1
    Star Lounger
    Join Date
    Aug 2003
    Location
    Brisbane, Queensland, Australia
    Posts
    86
    Thanks
    0
    Thanked 0 Times in 0 Posts

    C# writing to file (VS version 8)

    I am hoping someone out there will be able to help me with what is, I'm sure, a trivial thing. Some years ago, I did some programming in C and C+ but since then I have coded exclusively in VBA. I am now trying to get my head around C#. One thing I want to do is write settings to a file. I have them stored in a structure (they are a mixture of types). The code I used to write a structure to a file in C+ was:

    . . . .
    if(write(fp,sheet,sizeof(*sheet))!=sizeof(*sheet))
    { /* error writing file */
    error("Error! Worksheet file could not",
    "be written to. Write aborted!");
    return(0);
    }
    close(fp);

    I am at a loss as to find the equivalent in C#. I have found how to write text and binary characters but not a struct. Any ideas?

    Many thanks.

    Graeme.

  2. #2
    Super Moderator jscher2000's Avatar
    Join Date
    Feb 2001
    Location
    Silicon Valley, USA
    Posts
    23,112
    Thanks
    5
    Thanked 93 Times in 89 Posts

    Re: C# writing to file (VS version 8)


  3. #3
    Star Lounger
    Join Date
    Aug 2003
    Location
    Brisbane, Queensland, Australia
    Posts
    86
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Re: C# writing to file (VS version 8)

    Thanks for this. Unfortunately, it relates to writing text files. I can follow that. What I am looking for is the ability to essentially dump a structure into a file. At another place, I will need to read this file directly into the structure.

    Thank you for your suggestion.

    Graeme.

  4. #4
    Silver Lounger
    Join Date
    Jan 2001
    Location
    Indianapolis, Indiana, USA
    Posts
    1,862
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Re: C# writing to file (VS version 8)

    Hi Graeme,

    In the .NET world, settings are most frequently stored in XML format. You'll want to look at the XML Writer class.

    There's not really any built-in way in C# (that I know of) to write out a structure to a pre-determined format. You'll need to have some method to translate the structure (and its values) into the desired output format.

  5. #5
    3 Star Lounger
    Join Date
    Aug 2001
    Location
    Jeddah, Saudi Arabia
    Posts
    243
    Thanks
    0
    Thanked 1 Time in 1 Post

    Re: C# writing to file (VS version 8)

    Hi Greame,

    This kind of thing is done through object serialization in the .NET world. I quote from the help:

    Serialization can be defined as the process of storing the state of an object to a storage medium. During this process, the public and private fields of the object and the name of the class, including the assembly containing the class, are converted to a stream of bytes, which is then written to a data stream. When the object is subsequently deserialized, an exact clone of the original object is created.

    End of quote.

    My little program below shows how to serialize a simple class to a file then read it back. I hope it will be at least a start for you. For this I used the BinaryFormatter. There are other formatters available such as SOAP. Look in the System.Runtime.Serialization.Formatters namespace for further information.

    I use this method instead of .INI files. I don't have to worry about data conversion.

    I used VS 2.0 C# for this.

    using System;
    using System.IO;
    using System.Windows.Forms;
    using System.Runtime.Serialization;
    using System.Runtime.Serialization.Formatters.Binary;

    namespace Save_Structure
    {
    public partial class Form1 : Form
    {
    [Serializable]
    public struct mystruc
    {
    public int myint;
    public bool mybool;
    public string mystring;
    public double mydouble;


    public mystruc(int a, bool b, string c, double d)
    {
    myint=a;
    mybool=b;
    mystring=c;
    mydouble=d;
    }
    };

    public Form1()
    {
    InitializeComponent();
    }

    private void btnDoIt_Click(object sender, EventArgs e)
    {
    mystruc mst = new mystruc();
    mst.myint = 7;
    mst.mybool=true;
    mst.mystring="Some Text";
    mst.mydouble=99.999999;

    IFormatter formatter = new BinaryFormatter();
    Stream stream = new FileStream(@"c:MyStruct.bin", FileMode.Create, FileAccess.Write, FileShare.None);
    formatter.Serialize(stream, mst);
    stream.Close();

    // Read the file back and display the variables

    formatter = new BinaryFormatter();
    stream = new FileStream(@"c:MyStruct.bin", FileMode.Open, FileAccess.Read, FileShare.Read);
    mystruc obj = (mystruc)formatter.Deserialize(stream);
    // change the name of the object just to prove we don't have the values carried over
    stream.Close();

    // Here's the proof.
    Console.WriteLine("myint: {0}", obj.myint);
    Console.WriteLine("mybool: {0}", obj.mybool);
    Console.WriteLine("mystring: {0}", obj.mystring );
    Console.WriteLine("mydouble: {0}", obj.mydouble );

    this.Close();

    }
    }
    }


    Regards,
    Kevin Bell

  6. #6
    Star Lounger
    Join Date
    Aug 2003
    Location
    Brisbane, Queensland, Australia
    Posts
    86
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Re: C# writing to file (VS version 8)

    Thanks mark. I will have a look at this.

    Graeme.

  7. #7
    Star Lounger
    Join Date
    Aug 2003
    Location
    Brisbane, Queensland, Australia
    Posts
    86
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Re: C# writing to file (VS version 8)

    Kevin,

    Thanks for this - this is exactly what I was after. I appreciate the time you put into providing the example. It is very neat.

    If I may ask a supplementary question - the function I have written containing your code is in a ReadSettings function in a class called modLogFile.cs and passes the structure to a function in the frmMain (FORM1.cs) class. If the function in frmMain is declared as 'public static void', I can call it from the ReadSettings function but it does not appear to know about the fields on the form that the data is to be loaded into. I get 14 errors "An object reference is required for the nonstatic field, method, or property 'member'" that refer to the 14 fields on the form. If it is declared as 'public void', it knows about the fields it has to put data into but I can no longer call it from the ReadSettings function - I get the error "An object reference is required for the nonstatic field, method, or property 'member'" and refers to the called function that loads the read data into the form - in the ReadSettings function that calls it. The line that calls the function (and the error points to) is

    frmMain.LoadIniSettings(rdSettings);

    I suspect this has to do with my ignorance of what "static" really means. I have struck the same problem with a Progress Bar I want to update from several places (in different classes). I have wrwitten the update function in frmMain and have the same issue.

    Many thanks.

  8. #8
    3 Star Lounger
    Join Date
    Aug 2001
    Location
    Jeddah, Saudi Arabia
    Posts
    243
    Thanks
    0
    Thanked 1 Time in 1 Post

    Re: C# writing to file (VS version 8)

    Ah, the wonderful world of static.

    Whenever a process is loaded into memory you can imagine the memory being divided into roughly 3 parts within the process, Stack, Heap and Static. The static part holds the 'static' member variables and methods. Static methods and variables are those which don't require an instance of the class to be created, in other words, memory is already allocated for them. For example:

    class myClass
    {
    public static int a;
    public static void DoSomething();
    }

    These member variables and methods can be used without creating an instance of the enclosing class.

    However, an important thing to remember is that the static methods inside a class can only use static member variables of that class.

    So, in your case, when you declare your function in frmMain as 'public static void' it becomes callable from your modLogFile class as it doesn't need to be instantiated but can only access static variables inside the frmMain class and as your fields on the form are probably not declared as static they are invisible, well, not exactly invisible but the compiler gets all grumpy. When your function is declared as 'public void', no memory is allocated for it so you can't call it from your modLogFile class without instantiating the containing class but the fields become visible.

    The solution is to encapsulate all the functionality of the save and restore functions for your settings in the modLogFile class, then after the structure has been restored, transfer the data into the fields in the frmMain class.

    An important point to note is that a static class in C# is different from one in Java. In Java, the static modifier is used to make a member class a nested top level class inside a package. So using the static keyword with a class is different from using it with member variables or methods in Java.

    I hope this is not too confusing. Static confused the living daylights out of me at first but one day I had my epiphany as I am sure you will too.

    Regards,
    Kevin Bell

  9. #9
    Star Lounger
    Join Date
    Aug 2003
    Location
    Brisbane, Queensland, Australia
    Posts
    86
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Re: C# writing to file (VS version 8)

    Kevin,

    I am so pleased that I am not the only one who has trouble with this. I sort of follow what you say and, after reading it a few dozen times will probably start to see what it is all about. I take it that static methods and members can be seen outside their class (and therefore called an used).

    Your suggested solution "The solution is to encapsulate all the functionality of the save and restore functions for your settings in the modLogFile class, then after the structure has been restored, transfer the data into the fields in the frmMain class." is what I thought I was already doing - but I may have missed something here. Here is my logic:

    I read the file and put the structure together in modLogFile then pass the structure to the ReadSettings function in frmMain so it can put the values into the form. I cannot see the form fields in modLogFile so cannot enter them from there. To pass the structure to a function in frmMain, it must be static (my guess). If it is (and the form fields are not), it will not be able to put the data into the form fields. Do I need to create an instance of the frmMain class? if so, is this difficult?

    Oooohhhh - confusion is creeping in again!!! Just bail out of this as soon as you have had enough. I am very appreciative of your assistance.

    Many many thanks.

    Graeme.

  10. #10
    Star Lounger
    Join Date
    Aug 2003
    Location
    Brisbane, Queensland, Australia
    Posts
    86
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Re: C# writing to file (VS version 8)

    Kevin,

    I believe that I am nearly there. In the function in modLogFile that reads the settings, I put the following 2 lines (separated by some other stuff):

    frmMain fm = new frmMain();
    . . . . .
    fm.LoadIniSettings(rdSettings);

    This made the LoadIniSettings visible without it being static (have I created an instance of the class?). I did a messageBox.Show of one of the imported values from the LoadIniSettings functions and it contained the value that I was looking for. I got excited! However, the value is not showing on the form. I tried an Application.DoEvents(); hoping that it would force a refresh of the form but no luck. I figure I have nearly broken it (with a lot of help from you - ta). I wqill go away and find out now how to make the values show.

    Something I now remember liking about C - when you get something that should be trivial (and is in any other language) but is incredibly comlicated to actually work!

    Cheers.

    Graeme.

  11. #11
    3 Star Lounger
    Join Date
    Aug 2001
    Location
    Jeddah, Saudi Arabia
    Posts
    243
    Thanks
    0
    Thanked 1 Time in 1 Post

    Re: C# writing to file (VS version 8)

    Here's what I think is a better way to do this without creating a class for the saving and loading of the settings. Use subroutines instead. Yes, I know this is not pure OOP but I do actually think this is easier.

    Based on my previous example, look at this program.

    Long code fragment moved to attachment by HansV

    All this program does is declare the settings structure, mySettings. Assign it some values. Save it using the serializer. Change the values and display them to show they've changed. Restore the settings using the serializer and display them once more to show they have been restored.

    To run it you need a formcalled Form1 with a button on it called btnDoIt.

    The beauty of this method is that the code is in the main class, where the fields are so you don't have the problem of trying to reference fields in another class whether they are declared as static or not.

    I hope this helps.

    Cheers,
    Kevin Bell

    PS. Things like this are why I switched to coding in Visual Basic in .NET. It's sooooo much easier.

  12. #12
    Star Lounger
    Join Date
    Aug 2003
    Location
    Brisbane, Queensland, Australia
    Posts
    86
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Re: C# writing to file (VS version 8)

    OK - I found a way through this without bringing all my code into the frmMain. In frmMain, I created a structure and passed it by reference to the modLogFile function that read the settings into it. Then I updated the form from frmMain. It works! Heaps of thanks for your patience!

    I agree that it would actually be neater to bring it all into the same class but I have been given the task of completing an application that has already created the modLogFile class and put stuff into it - so I was trying to preserve it. And I also thought I might learn something along the way - which I certainly did.

    Graeme.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •