在我的文件浏览器应用程序中,我试图在任何文件夹中只显示xml文件。所以每次打开文件夹时,我只想显示xml文件。我查看了这个网站和互联网上有大量的例子,但是在C#中找不到一个例子。我也尝试根据我的需要修改其他例子,但是我实施了IFileNameFilter类。有人知道吗怎么做?我试图实现它,但不断出现构建错误。
在下面的代码中,我有一个显示文件的ListFragment类:
public override void OnListItemClick(ListView l, View v, int position, long id)
{
try{
var fileSystemInfo = _adapter.GetItem(position);
if (fileSystemInfo.IsFile())
{
// Do something with the file. In this case we just pop some toast.
Log.Verbose("FileListFragment", "The file {0} was clicked.", fileSystemInfo.FullName);
Toast.MakeText(Activity, "You selected file " + fileSystemInfo.FullName, ToastLength.Short).Show();
OnFileClick (fileSystemInfo);
}
else
{
// Dig into this directory, and display it's contents
RefreshFilesList(fileSystemInfo.FullName);
}
}catch(Exception e){
Log.Error (TAG,e.ToString());
}
base.OnListItemClick(l, v, position, id);
}
public void RefreshFilesList(string directory)
{
//GenericExtFilter filter = new GenericExtFilter(extension);
IList<FileSystemInfo> visibleThings = new List<FileSystemInfo>();
var dir = new DirectoryInfo(directory);
try
{
foreach (var item in dir.GetFileSystemInfos().Where(item => item.IsVisible()))
{
visibleThings.Add(item);
}
}
catch (Exception ex)
{
Log.Error("FileListFragment", "Couldn't access the directory " + _directory.FullName + "; " + ex);
Toast.MakeText(Activity, "Problem retrieving contents of " + directory, ToastLength.Long).Show();
return;
}
_directory = dir;
_adapter.AddDirectoryContents(visibleThings);
// If we don't do this, then the ListView will not update itself when the data set
// in the adapter changes. It will appear to the user that nothing has happened.
ListView.RefreshDrawableState();
Log.Verbose("FileListFragment", "Displaying the contents of directory {0}.", directory);
}
答案 0 :(得分:1)
如果我理解正确,你想创建将过滤XML文件的IFilenameFilter。
public class XmlFileFilter : Java.Lang.Object, IFilenameFilter
{
public bool Accept(File dir, string filename)
{
return filename.ToLower().EndsWith(".xml");
}
}
答案 1 :(得分:-1)
我用一个简化的解决方案解决了这个问题。毕竟我没有使用IFileNameFilter。在上面的RefreshFilesList方法中,我进行了以下更改:
foreach (var item in dir.GetFileSystemInfos().Where(item => item.IsVisible()))
{
if(item.IsDirectory())
{
visibleThings.Add(item);
}else if(item.IsFile())
{
bool isXmlFile = item.Extension.ToLower().EndsWith("xml");
if(isXmlFile)
{
visibleThings.Add(item);
}
}
}
现在显示所有文件夹和任何xml文件。