Skip to content Skip to sidebar Skip to footer

Android Fileobserver Example In Xamarin/c#?

I need guidance in creating a file observer in Xamarin c# (Android) Some sort of workable example would be wonderful ! I've tried to convert the java ones over to C# but due to my

Solution 1:

Create a class that inherits from Android.OS.FileObserver, you only need to implement the OnEvent() and one(+) Constructors. Its a really simple pattern after you see it once... ;-)

Notes:

  • Watch on a path, if you need to filter by file, do it in the OnEvent
  • Do not let your FileObserver object get GC'd or your OnEvents will magically stop :-/
  • Remember to call StartWatching() in order to receive OnEvent calls

FileObserver Class:

using System;
using Android.OS;
using Android.Util;

namespaceMyFileObserver
{
    publicclassMyPathObserver : Android.OS.FileObserver
    {
        staticFileObserverEvents _Events = (FileObserverEvents.AllEvents);
        conststring tag = "StackoverFlow";

        publicMyPathObserver (String rootPath) : base(rootPath, _Events)
        {
            Log.Info(tag, String.Format("Watching : {0}", rootPath)); 
        }

        publicMyPathObserver (String rootPath, FileObserverEvents events) : base(rootPath, events)
        {
            Log.Info(tag, String.Format("Watching : {0} : {1}", rootPath, events)); 
        }

        public override voidOnEvent(FileObserverEvents e, String path)
        {
            Log.Info(tag, String.Format("{0}:{1}",path, e)); 
        }
    }
}

Example Usage:

var pathToWatch = System.Environment.GetFolderPath (System.Environment.SpecialFolder.Personal);
// Do not let myFileObserver get GC'd, stash it's ref in an activty, or ...
myFileObserver = newMyPathObserver (pathToWatch);
myFileObserver.StartWatching (); // and StopWatching () when you are done...vardocument = Path.Combine(pathToWatch, "StackOverFlow.txt");
button.Click += delegate {
    if (File.Exists (document)) {
        button.Text = "Delete File";
        File.Delete (document);
    } else {
        button.Text = "Create File";
        File.WriteAllText (document, "Foobar");
    }
};

adb logcat Output (when clicking on the test button):

I/StackoverFlow( 3596): StackOverFlow.txt:Create
I/StackoverFlow( 3596): StackOverFlow.txt:Open
I/StackoverFlow( 3596): StackOverFlow.txt:Modify
I/StackoverFlow( 3596): StackOverFlow.txt:CloseWrite
I/StackoverFlow( 3596): StackOverFlow.txt:Delete
I/StackoverFlow( 3596): StackOverFlow.txt:Create
I/StackoverFlow( 3596): StackOverFlow.txt:Open
I/StackoverFlow( 3596): StackOverFlow.txt:Modify
I/StackoverFlow( 3596): StackOverFlow.txt:CloseWrite
I/StackoverFlow( 3596): StackOverFlow.txt:Delete
I/StackoverFlow( 3596): StackOverFlow.txt:Create
I/StackoverFlow( 3596): StackOverFlow.txt:Open
I/StackoverFlow( 3596): StackOverFlow.txt:Modify
I/StackoverFlow( 3596): StackOverFlow.txt:CloseWrite

Post a Comment for "Android Fileobserver Example In Xamarin/c#?"