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!
Explore My Other Channel for More Cool and Valuable Insights
👉 Youtube Learn Tech Tips👉 Tiktok
👉 Facebook: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!
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)
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 ✋✋✋✋