如何使用Vala监视〜/.local目录? [英] How can I monitor the ~/.local directory using Vala?

查看:86
本文介绍了如何使用Vala监视〜/.local目录?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试根据 Vala监视〜/.local目录文档我可以正确地监控房屋.但我无法监视〜/.local.

I am trying to monitor the ~/.local directory according to the Vala documentation I can monitor the home correctly. but I can't monitor the the ~/.local.

public void initFileMonitor(){
    try {
        string homePath = Environment.get_home_dir();
        string filePath = homePath + "/.local";
        File file = File.new_for_path(filePath);
        FileMonitor monitor = file.monitor_directory(FileMonitorFlags.NONE, null);

        print ("\nMonitoring: %s\n", file.get_path ());

        monitor.changed.connect ((src, dest, event) => {
            if (dest != null) {
                 print ("%s: %s, %s\n", event.to_string (), src.get_path (), dest.get_path ());
            } else {
                print ("%s: %s\n", event.to_string (), src.get_path ());
            }
        });
    } catch (Error err) {
        print ("Error: %s\n", err.message);
    }
}

终端输出(无错误,无监视):

Monitoring: /home/srdr/.local

推荐答案

由于文件监视器存储在本地变量中,因此就像在函数调用结束时销毁其他变量(或用GObject术语确定/销毁)一样,

Because the file monitor is stored in a local variable it is like other variables destroyed (or in GObject terms finalised/destructed) at the end of the function call

为确保其寿命足够长,您应该将其设置为类的一个字段,然后FileMonitor实例由该类的实例拥有",而不是每次调用特定方法

To ensure it lives long enough you should make it a field on a class, then the FileMonitor instance is 'owned' by an instance of that class rather than each call to a specific method

可运行的演示(valac demo.vala --pkg gio-2.0)

class FileMonitorDemo {
    private FileMonitor monitor;

    public void initFileMonitor() {
        var path = Path.build_filename(Environment.get_home_dir(), ".local");
        var file = File.new_for_path(path);
        try {
            monitor = file.monitor_directory(NONE);

            message ("Monitoring: %s", file.get_path ());

            monitor.changed.connect ((src, dest, event) => {
                if (dest != null) {
                    print ("%s: %s, %s\n", event.to_string (), src.get_path (), dest.get_path ());
                } else {
                    print ("%s: %s\n", event.to_string (), src.get_path ());
                }
            });
        } catch (Error err) {
            critical ("Error: %s\n", err.message);
        }
    }
}

void main () {
    var filemon = new FileMonitorDemo();
    filemon.initFileMonitor();
    new MainLoop ().run ();
}

这篇关于如何使用Vala监视〜/.local目录?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆