[Mono-list] Pattern Matching to Find Files

Jonathan Pryor jonpryor at vt.edu
Tue Jan 3 20:58:32 EST 2006


On Tue, 2006-01-03 at 17:06 -0500, Abe Gillespie wrote:
> I'd like to use Directory.GetFiles() to get all the files that don't
> HAVE an extension.  Is there a pattern I can send into GetFiles()
> that'll do the trick?  ... I guess the pattern needs to match when
> there is NO dot.

You could use Mono.Unix.UnixDirectoryInfo.GetFileSystemEntries() (in
Mono.Posix.dll) which takes a regular expression:

	using Mono.Unix;

	UnixFileSystemInfo[] dirents = 
	  new UnixDirectoryInfo ("dir").GetFileSystemEntries ("^[^.]+$");

The downside is this returns files, directories, symbolic links,
sockets...  Everything within the directory.  If you want to narrow this
down to files, you'll need additional work:

        private static UnixFileInfo GetFile (UnixFileSystemInfo f)
        {
          if (f.IsSymbolicLink) {
            UnixSymbolicLinkInfo s = (UnixSymbolicLinkInfo) f;
            if (s.Contents.IsRegularFile)
              return (UnixFileInfo) s.Contents;
            return null;
          }
          if (f.IsRegularFile)
            return (UnixFileInfo) f;
          return null;
        }

        public static UnixFileInfo[] GetFiles (string dir)
        {
          UnixFileSystemInfo[] dirents = 
            new UnixDirectoryInfo (dir).GetFileSystemEntries
        ("^[^.]+$");
          int num_files = 0;
          foreach (UnixFileSystemInfo d in dirents) { 
            if (GetFile (d) != null)
              ++num_files;
          }
          UnixFileInfo[] files = new UnixFileInfo[num_files];
          num_files = 0;
          foreach (UnixFileSystemInfo d in dirents) { 
            UnixFileInfo f = GetFile (d);
            if (f != null) {
              files [num_files++] = f;
            }
          }
          return files;
        }

It goes without saying that this is specific to Unix platforms.

 - Jon




More information about the Mono-list mailing list