ObservedBinaryFile

The ObservedBinaryFile allows you to subscribe to file change events for a specific file. It uses the FileSystemWatcher class to monitor the file for changes, and notifies subscribers when the file is changed, created, deleted, or renamed.

Note that the Created type is also used when writing all bytes to the file, i.e. replacing all of its content. Additionally, when the file is moved, the Renamed type will be used.

Usage

To use ObservedBinaryFile, create an instance of the class and pass the path to the file you want to monitor as an argument to the constructor. Then, you can subscribe to file change events by calling the Subscribe method and passing a callback function as an argument. The callback function will be called with the file's contents as a byte[] and the type of change that occurred (created, changed, deleted, or renamed).

Here is an example of how to use ObservedBinaryFile in a Unity MonoBehaviour class:

using Observed;
using UnityEngine;

public class FileMonitor : MonoBehaviour
{
    private ObservedBinaryFile _observedFile;

    private void Start()
    {
        _observedFile = new ObservedBinaryFile("my_file.bin");
        _observedFile.Subscribe(OnFileChanged);
    }

    private void OnFileChanged(byte[] contents, WatcherChangeTypes type)
    {
        Debug.Log($"File changed: {type}");
        // Do something with the file contents
    }
}

You can also unsubscribe from file change events by calling the Unsubscribe method and passing the callback function as an argument, or clear all subscribers by calling the ClearSubscriptions method.

In addition to subscribing to file change events, you can also use ObservedBinaryFile to read and write the contents of the file using the ReadAllBytes and WriteAllBytes methods, move the file using the Move method, and append bytes to the end of the file using the AppendBytes method.

Last updated