Background
Break News
How to add local font to Tailwind Css and NextJS? - Tutorial Design Pattern? - Blockchain Technology, How to create own Bitcoin virtual currency - Zustand mordern management state - Design Pattern - Flyweight Pattern? - Docker Full training Topic

[Tips] How to "read and write struct file with C# programming language"

Tuesday 1 May 2018
|
Read: Completed in minutes

[Tips] How to "read and write struct file with C# programming language"

In this article, I will teach you how to write a structure file in CSharp. A structure file is a type of binary file that stores data in a predefined format. You can use a structure file to save and load data efficiently, or to exchange data between different programs or systems.

To write a structure file in CSharp, you need to follow these steps:

How to "read and write struct file with C# programming language"


•  First, you need to define a structure that represents the data you want to store. A structure is a way of grouping multiple variables of different types into one unit. For example, you can create a structure called Student that contains the name, age, and grade of a student.

•  Second, you need to create an instance of the structure and assign values to its variables. An instance is a specific example of the structure that holds actual data. For example, you can create a student named Zidane who is 25 years old and has a grade of 4.0.

•  Third, you need to use the BinaryWriter class to write the instance of the structure to a binary file. The BinaryWriter class is a tool that allows you to write basic data types, such as numbers and strings, to a stream of bytes. A stream is an abstract concept that represents a source or destination of bytes, such as a file or a network connection. You can use the FileStream class to create a stream that connects to a file on your disk.

•  Fourth, you need to close the BinaryWriter and FileStream objects after writing the data. This will ensure that the data is properly saved and that the resources are released.

•  Fifth, you can use the BinaryReader class to read the instance of the structure from the binary file. The BinaryReader class is a tool that allows you to read basic data types from a stream of bytes. You can use the same FileStream class to create a stream that connects to the same file on your disk.

•  Sixth, you can display the values of the variables on your console or use them for other purposes. This will confirm that the data is correctly written and read from the binary file.

By following these steps, you can write a structure file in CSharp easily and quickly. This technique can help you manage and manipulate data in various scenarios. If you want to learn more about structures, binary files, and streams in CSharp, please check out the links below. If you have any questions or comments, please feel free to leave them below. Thank you for reading and happy coding!









After write struct into file, you will see format file same as below picture, The reader can't read it well, because you write with struct file!

How to read and write struct file with C# programming language

Okay now. Let's start how to do it!

This is my demo GUI
I have one struct with 5 params from 1 to 5 include:

param1: (string)
param2: (int)
param3: (double)
param4: (datetime)
param5: (char)

How to read and write struct file with C# programming language
Here is MyParams struct
public struct MyParams
{
    public string par1;
    public int par2;
    public double par3;
    public DateTime par4;
    public char par5;
}

	
    

Next, create the structFile Class with init file, init structure use Marshal class
public class StructFile
{
    private object _oStruct = null;
    private System.Type _stuctureType = null;
    private string _pathOfFile = null;
    private FileStream _fs = null;   

    public   StructFile(string szFile, System.Type type)
    {
            _pathOfFile = szFile;
            _stuctureType = type;
    }
 
    private void LoadFileStream(FileMode FileMode, FileAccess FileAccess, FileShare FileShare)
    {
            if (_fs == null)
            {
                try
                {
                    _fs = new FileStream(_pathOfFile, FileMode, FileAccess, FileShare);
                }
                catch (Exception ex)
                {
                    throw ex;
                }
            }
    }
 
   public bool EOF             //End of File
   {
            get
            {
                if (_fs != null)
                {
                    if (_fs.Position >= _fs.Length)
                        Close();
                }
 
                return _fs == null;
            }
   }
 
   private byte[] StructToByteArray()
   {
       try
       {
          // This function copys the structure data into a byte[]
          // Set the buffer ot the correct size
          byte[] buffer = new byte[Marshal.SizeOf(_oStruct)];
                
          // Allocate the buffer to memory and pin it so that GC cannot use the space (Disable GC)
          GCHandle h = GCHandle.Alloc(buffer, GCHandleType.Pinned);
 
          // Copy the struct into int byte[] mem alloc 
          Marshal.StructureToPtr(_oStruct, h.AddrOfPinnedObject(), false);
 
          // Allow GC Free. Because u use Marshal so GC will dont Free your memory until you call GC.Free
          h.Free();
 
          // return the byte[]
          return buffer;                                                                                         
       }
       catch (Exception ex)
       {
          throw ex;
       }
   }
 
 
   public bool WriteStructure(object oStruct)
   {
            _oStruct = oStruct;
            try
            {
                byte[] buf = StructToByteArray();
 
                BinaryWriter bw = new BinaryWriter(_fs);
 
                bw.Write(buf);
 
                bw.Close();
                bw = null;
 
                return true;
            }
            catch (Exception ex)
            {
                throw ex;
            }
   }
 
   public object GetStructureValue()
   {
       byte[] buffer = new byte[Marshal.SizeOf(_stuctureType)];
 
       object oReturn = null;
 
       try
       {
           if (EOF) return null;
 
           _fs.Read(buffer, 0, buffer.Length); 
           GCHandle handle = GCHandle.Alloc(buffer, GCHandleType.Pinned);
           oReturn = (object)Marshal.PtrToStructure(handle.AddrOfPinnedObject(), _stuctureType);
           handle.Free();
 
           if (_fs.Position >= _fs.Length)
               Close();
 
           return oReturn;
       }
       catch (Exception ex)
       {
           throw ex;
       }
  }
 
  public void Close()         //Close the file stream
  {
            if (_fs != null)
            {
                _fs.Close();
                _fs = null;
            }
            GC.Collect();
  }
 
  public void Open(FileMode FileMode, FileAccess FileAccess, FileShare FileShare)
  {
      LoadFileStream(FileMode, FileAccess, FileShare);
  }
}

On Main Form
We use below btnCreateFile_Click function to write structure file

with _path is
_path = Path.Combine(Application.StartupPath, "file.dat");

private void btnCreateFile_Click(object sender, EventArgs e)
{
    MyParams p = new MyParams();
 
    try
    {
               p.par1 = txtpa1.Text;
               p.par2 = Convert.ToInt32(txtpa2.Text);
               p.par3 = Convert.ToDouble(txtpa3.Text);
               p.par4 = dtpa4.Value;
               p.par5 = Convert.ToChar(txtpa5.Text);
     }
     catch (Exception ex)
     {
         MessageBox.Show(this"Invalid Data entered\r\n" + ex.Message);
         return;
     }
 
     try
     {
              
         StructFile sf = new StructFile(_path, typeof(MyParams));
         sf.Open(System.IO.FileMode.Append, System.IO.FileAccess.Write, System.IO.FileShare.None);
 
         sf.WriteStructure((object)p);
 
         sf.Close();
         MessageBox.Show(this"Saved Succeed!");
    }
    catch (Exception ex)
    {                
         MessageBox.Show(this, ex.Message);
    }
}

We use btnViewBinaryRecord_Click function to read info from binary file


private void btnViewBinaryRecord_Click(object sender, EventArgs e)
{
    MyParams p = new MyParams();
 
    StructFile sfRead = new StructFile(_path, typeof(MyParams));
    sfRead.Open(System.IO.FileMode.Open, System.IO.FileAccess.Read, System.IO.FileShare.ReadWrite);
 
    p = (MyParams)sfRead.GetStructureValue();
 
    string temp = p.par1 + Environment.NewLine;
    temp += p.par2.ToString() + Environment.NewLine;
    temp += p.par3.ToString() + Environment.NewLine;
    temp += p.par4.ToShortDateString() + Environment.NewLine;
    temp += p.par5.ToString();
 
    MessageBox.Show(temp);
}


Or you can download my full source code from below link

Link Download here 👉 Live Demo




Thank you for reading this post. I hope you found it helpful and easy to follow. If you have any feedback or questions about How to "read and write struct file with C# programming language" , please share them in the comments below. I would love to hear from you and discuss this topic further
✋✋✋✋  Webzone Tech Tips  - I am Zidane, See you next time soon ✋✋✋✋

🙇🏼 Your Feedback Is Valuable and Helpful to Us - Webzone - all things Tech Tips web development Zidane 🙇🏼
Popular Webzone Tech Tips topic maybe you will be like it - by Webzone Tech Tips - Zidane
As a student, I found Blogspot very useful when I joined in 2014. I have been a developer for years . To give back and share what I learned, I started Webzone, a blog with tech tips. You can also search for tech tips zidane on Google and find my helpful posts. Love you all,

I am glad you visited my blog. I hope you find it useful for learning tech tips and webzone tricks. If you have any technical issues, feel free to browse my posts and see if they can help you solve them. You can also leave a comment or contact me if you need more assistance. Here is my blog address: https://learn-tech-tips.blogspot.com.

My blog where I share my passion for web development, webzone design, and tech tips. You will find tutorials on how to build websites from scratch, using hot trends frameworks like nestjs, nextjs, cakephp, devops, docker, and more. You will also learn how to fix common bugs on development, like a mini stackoverflow. Plus, you will discover how to easily learn programming languages such as PHP (CAKEPHP, LARAVEL), C#, C++, Web(HTML, CSS, javascript), and other useful things like Office (Excel, Photoshop). I hope you enjoy my blog and find it helpful for your projects. :)

Thanks and Best Regards!
Follow me on Tiktok @learntechtips and send me a direct message. I will be happy to chat with you.
Webzone - Zidane (huuvi168@gmail.com)
I'm developer, I like code, I like to learn new technology and want to be friend with people for learn each other
I'm a developer who loves coding, learning new technologies, and making friends with people who share the same passion. I have been a full stack developer since 2015, with more than years of experience in web development.
Copyright @2022(November) Version 1.0.0 - By Webzone, all things Tech Tips for Web Development Zidane
https://learn-tech-tips.blogspot.com