问题描述
我想将文件添加到列表中,然后在 for 循环中访问它们。这就是我尝试这样做的方式:
private get_app_list () {
var file = new File.new_for_path (/usr/share/applications);
List<File> app_list = new List<File> ();
foreach (File desktop_file in app_list) {
// other code here
}
}
访问存储在目录中的文件然后将它们添加到列表的正确方法是什么?
解决方法
using Posix;
...
List<File> app_list = new List<File> ();
//Open directory. Returns null on error
var dirHandle = Posix.opendir("/usr/share/applications");
unowned DirEnt entry;
//While there is an entry to read in the directory
while((entry = readdir(dir)) != null) {
//Get the name
var name = (string) entry.d_name;
//And add a new file to the app_list
app_list.add(new File.new_for_path("/usr/share/applications"+name);
}
,
如果您只想显示系统上可用的应用程序,您可以使用 Gio-2.0
库提供的实用程序。将 dependency ('gio-2.0'),
添加到您的 meson.build
文件后,您可以使用类似于以下内容的代码:
/* We use a `GListStore` here,which is a simple array-like list implementation
* for manual management.
* List models need to know what type of data they provide,so we need to
* provide the type here. As we want to do a list of applications,`GAppInfo`
* is the object we provide.
*/
var app_list = new GLib.ListStore (typeof (GLib.AppInfo));
var apps = GLib.AppInfo.get_all ();
foreach (var app in apps) {
app_list.append (app);
}
但是,如果您需要列出目录中的文件,也可以使用同一个 gio-2.0
库提供的更高级别的 API。下面是一个示例代码,用于枚举 "/usr/share/applications/"
void main () {
var app_dir = GLib.File.new_for_path ("/usr/share/applications");
try {
var cancellable = new Cancellable ();
GLib.FileEnumerator enumerator = app_dir.enumerate_children (
GLib.FileAttribute.STANDARD_DISPLAY_NAME,GLib.FileQueryInfoFlags.NOFOLLOW_SYMLINKS,cancellable
);
FileInfo ? file_info = null;
while (!cancellable.is_cancelled () &&
((file_info = enumerator.next_file (cancellable)) != null)) {
// Ignore directories
if (file_info.get_file_type () == GLib.FileType.DIRECTORY) {
continue;
}
// files could be added to a list_store here.
/*
* var files_list = new GLib.ListStore (typeof (GLib.FileInfo));
* files_list.append (file_info);
*/
print (file_info.get_display_name () + "\n");
}
} catch (GLib.Error err) {
info ("%s\n",err.message);
}
}
我希望这能有所帮助。