generic class for saving and loading files in csharp

main.cs
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;

namespace YourNamespace
{
    public static class FileManager<T>
    {
        public static void Save(string filePath, T data)
        {
            FileStream fileStream = null;

            try
            {
                fileStream = new FileStream(filePath, FileMode.Create);
                BinaryFormatter formatter = new BinaryFormatter();
                formatter.Serialize(fileStream, data);
            }
            finally
            {
                if (fileStream != null)
                {
                    fileStream.Close();
                }
            }
        }

        public static T Load(string filePath)
        {
            FileStream fileStream = null;

            try
            {
                fileStream = new FileStream(filePath, FileMode.Open);
                BinaryFormatter formatter = new BinaryFormatter();
                return (T)formatter.Deserialize(fileStream);
            }
            finally
            {
                if (fileStream != null)
                {
                    fileStream.Close();
                }
            }
        }
    }
}
1189 chars
47 lines

This code defines a static generic class FileManager with two methods: Save and Load. The Save method takes a string argument representing the file path where the data should be saved, and a second argument of type T representing the data to be saved. The Load method takes a string argument representing the file path from where the data should be loaded, and returns an instance of type T representing the loaded data.

The BinaryFormatter class is used for serialization and deserialization of an object in binary format. In the Save method, the BinaryFormatter object serializes the data to the specified file path. In the Load method, the BinaryFormatter object deserializes the data from the specified file path and returns the data as an instance of T.

Note that the T type parameter constraint is not specified in this implementation, so any type can be used with this class. If there are certain types that are not serializable, it would be best to add a constraint to prevent them from being used with this class.

gistlibby LogSnag