Jump to content
Search In
  • More options...
Find results that contain...
Find results in...

[C#] Saving data to .DAT files


Matt
 Share

Recommended Posts

So you've got some data you want to save to a file, but you don't know how? Then this tutorial is for you.

_**DISCLAIMER:**_ I am a self taught programmer. The method I present before you in this tutorial might not be the best method, but it works.

I'll be using a brand new console application. It looks something like this.

```

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace DataApplication
{
class Program
{
static void Main(string[] args)
{

}
}
}

```
Now, the first thing you should do is declare the IO namespace. This namespace lets us use the filesystem, so we can manipulate files. Put the Using statement right below the other Using statements.

```

// Input Output Namespace
using System.IO;

```
We should also create a static variable that holds the startup path of the program.

```

private static string StartupPath = AppDomain.CurrentDomain.BaseDirectory;

```
We'll now create two new methods (doesn't matter if they're public or private) called LoadData and SaveData that both return void.

```

private static void LoadData()
{

}

private static void SaveData()
{

}

```
Now, in our Main method, we'll type out this if statement.

```

static void Main(string[] args)
{
if (File.Exists(StartupPath + "\\DataFile.dat")) // Does the file exist?
{
LoadData(); // Yup
}
else
{
SaveData(); // Nope
}
}

```
Now, we can get to the actual saving and loading of data. Let's start with the method SaveData.

```

private static void SaveData()
{
MemoryStream Memory = new MemoryStream(); // Create a new memory stream to store data
BinaryWriter Writer = new BinaryWriter(Memory); // Create a binary writer that will write to the memory stream

// Write in all the data we want to store.
Writer.Write(5);
Writer.Write("String");
Writer.Write(true);

// Convert the memory stream to a byte array, and write the bytes to the data file.
File.WriteAllBytes(StartupPath + "\\DataFile.dat", Memory.ToArray());

Memory.Close(); // Dispose of the memory stream
}

```
Now, from my understanding, we create a new MemoryStream where we can store data to memory. The BinaryWriter will write any value you give it to the MemoryStream. Memory.ToArray() converts the stored memory to a byte array, and the method File.WriteAllBytes lets us write binary Byte array data to a file.

Now, we move on to the loading of data.

```

private static void LoadData()
{
byte[] FileByteArray; // Create a byte array to store the file contents
FileByteArray = File.ReadAllBytes(StartupPath + "\\DataFile.dat"); // Read all the bytes from the data file

MemoryStream Memory = new MemoryStream(FileByteArray); // Send all the data to a new memory stream so we can read from it
BinaryReader Reader = new BinaryReader(Memory); // Create a binary reader to read all the data in the memory stream

// Read the data
int Number = Reader.ReadInt32();
string Text = Reader.ReadString();
bool Boolean = Reader.ReadBoolean();

Memory.Close(); // Dispose of the memory stream
}

```
Again, from my understanding, File.ReadAllBytes gets the binary data from the file, and we store it in a new MemoryStream. We create a BinaryReader to read the data stored in the MemoryStream in a similar way as we stored it.

And that's pretty much it. Hope you learned something new! Feel free to give me any constructive criticism.
Link to comment
Share on other sites

Don't forget to wrap your disposable objects in a using statement. This will ensure that your IDisposable objects are disposed and your streams closed when scope is lost for those objects.

```

private static void LoadData()
{
byte[] FileByteArray; // Create a byte array to store the file contents
FileByteArray = File.ReadAllBytes(StartupPath + "\\DataFile.dat"); // Read all the bytes from the data file

using (MemoryStream Memory = new MemoryStream(FileByteArray)) // Send all the data to a new memory stream so we can read from it
{
using (BinaryReader Reader = new BinaryReader(Memory)) // Create a binary reader to read all the data in the memory stream
{
// Read the data
int Number = Reader.ReadInt32();
string Text = Reader.ReadString();
bool Boolean = Reader.ReadBoolean();
}
}
}

```
I made a slight modification to your code to reflect this change. It's good practice, nice tutorial!
Link to comment
Share on other sites

> Don't forget to wrap your disposable objects in a using statement. This will ensure that your IDisposable objects are disposed and your streams closed when scope is lost for those objects. I made a slight modification to your code to reflect this change. It's good practice, nice tutorial!

Hey! Thank you for the suggestion! But doesn't that just remove the necessity of calling Writer.Close() and Memory.Close() at the end of the method? I'm not an expert, so I might be wrong.
Link to comment
Share on other sites

> Hey! Thank you for the suggestion! But doesn't that just remove the necessity of calling Writer.Close() and Memory.Close() at the end of the method? I'm not an expert, so I might be wrong.

If an exception is raised, Close() will not be invoked unless you include Close() in a finally { } block.
Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
 Share

×
×
  • Create New...