FileSelector.cs 61 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612
  1. //#define SelectorTrace
  2. // FileSelector.cs
  3. // ------------------------------------------------------------------
  4. //
  5. // Copyright (c) 2008-2011 Dino Chiesa.
  6. // All rights reserved.
  7. //
  8. // This code module is part of DotNetZip, a zipfile class library.
  9. //
  10. // ------------------------------------------------------------------
  11. //
  12. // This code is licensed under the Microsoft Public License.
  13. // See the file License.txt for the license details.
  14. // More info on: http://dotnetzip.codeplex.com
  15. //
  16. // ------------------------------------------------------------------
  17. //
  18. // last saved: <2011-August-05 11:03:11>
  19. //
  20. // ------------------------------------------------------------------
  21. //
  22. // This module implements a "file selector" that finds files based on a
  23. // set of inclusion criteria, including filename, size, file time, and
  24. // potentially file attributes. The criteria are given in a string with
  25. // a simple expression language. Examples:
  26. //
  27. // find all .txt files:
  28. // name = *.txt
  29. //
  30. // shorthand for the above
  31. // *.txt
  32. //
  33. // all files modified after January 1st, 2009
  34. // mtime > 2009-01-01
  35. //
  36. // All .txt files modified after the first of the year
  37. // name = *.txt AND mtime > 2009-01-01
  38. //
  39. // All .txt files modified after the first of the year, or any file with the archive bit set
  40. // (name = *.txt AND mtime > 2009-01-01) or (attribtues = A)
  41. //
  42. // All .txt files or any file greater than 1mb in size
  43. // (name = *.txt or size > 1mb)
  44. //
  45. // and so on.
  46. // ------------------------------------------------------------------
  47. using System;
  48. using System.IO;
  49. using System.Text;
  50. using System.Reflection;
  51. using System.ComponentModel;
  52. using System.Text.RegularExpressions;
  53. using System.Collections.Generic;
  54. #if SILVERLIGHT
  55. using System.Linq;
  56. #endif
  57. namespace Ionic
  58. {
  59. /// <summary>
  60. /// Enumerates the options for a logical conjunction. This enum is intended for use
  61. /// internally by the FileSelector class.
  62. /// </summary>
  63. internal enum LogicalConjunction
  64. {
  65. NONE,
  66. AND,
  67. OR,
  68. XOR,
  69. }
  70. internal enum WhichTime
  71. {
  72. atime,
  73. mtime,
  74. ctime,
  75. }
  76. internal enum ComparisonOperator
  77. {
  78. [Description(">")]
  79. GreaterThan,
  80. [Description(">=")]
  81. GreaterThanOrEqualTo,
  82. [Description("<")]
  83. LesserThan,
  84. [Description("<=")]
  85. LesserThanOrEqualTo,
  86. [Description("=")]
  87. EqualTo,
  88. [Description("!=")]
  89. NotEqualTo
  90. }
  91. internal abstract partial class SelectionCriterion
  92. {
  93. internal virtual bool Verbose
  94. {
  95. get;set;
  96. }
  97. internal abstract bool Evaluate(string filename);
  98. [System.Diagnostics.Conditional("SelectorTrace")]
  99. protected static void CriterionTrace(string format, params object[] args)
  100. {
  101. //System.Console.WriteLine(" " + format, args);
  102. }
  103. }
  104. internal partial class SizeCriterion : SelectionCriterion
  105. {
  106. internal ComparisonOperator Operator;
  107. internal Int64 Size;
  108. public override String ToString()
  109. {
  110. StringBuilder sb = new StringBuilder();
  111. sb.Append("size ").Append(EnumUtil.GetDescription(Operator)).Append(" ").Append(Size.ToString());
  112. return sb.ToString();
  113. }
  114. internal override bool Evaluate(string filename)
  115. {
  116. System.IO.FileInfo fi = new System.IO.FileInfo(filename);
  117. CriterionTrace("SizeCriterion::Evaluate('{0}' [{1}])",
  118. filename, this.ToString());
  119. return _Evaluate(fi.Length);
  120. }
  121. private bool _Evaluate(Int64 Length)
  122. {
  123. bool result = false;
  124. switch (Operator)
  125. {
  126. case ComparisonOperator.GreaterThanOrEqualTo:
  127. result = Length >= Size;
  128. break;
  129. case ComparisonOperator.GreaterThan:
  130. result = Length > Size;
  131. break;
  132. case ComparisonOperator.LesserThanOrEqualTo:
  133. result = Length <= Size;
  134. break;
  135. case ComparisonOperator.LesserThan:
  136. result = Length < Size;
  137. break;
  138. case ComparisonOperator.EqualTo:
  139. result = Length == Size;
  140. break;
  141. case ComparisonOperator.NotEqualTo:
  142. result = Length != Size;
  143. break;
  144. default:
  145. throw new ArgumentException("Operator");
  146. }
  147. return result;
  148. }
  149. }
  150. internal partial class TimeCriterion : SelectionCriterion
  151. {
  152. internal ComparisonOperator Operator;
  153. internal WhichTime Which;
  154. internal DateTime Time;
  155. public override String ToString()
  156. {
  157. StringBuilder sb = new StringBuilder();
  158. sb.Append(Which.ToString()).Append(" ").Append(EnumUtil.GetDescription(Operator)).Append(" ").Append(Time.ToString("yyyy-MM-dd-HH:mm:ss"));
  159. return sb.ToString();
  160. }
  161. internal override bool Evaluate(string filename)
  162. {
  163. DateTime x;
  164. switch (Which)
  165. {
  166. case WhichTime.atime:
  167. x = System.IO.File.GetLastAccessTime(filename).ToUniversalTime();
  168. break;
  169. case WhichTime.mtime:
  170. x = System.IO.File.GetLastWriteTime(filename).ToUniversalTime();
  171. break;
  172. case WhichTime.ctime:
  173. x = System.IO.File.GetCreationTime(filename).ToUniversalTime();
  174. break;
  175. default:
  176. throw new ArgumentException("Operator");
  177. }
  178. CriterionTrace("TimeCriterion({0},{1})= {2}", filename, Which.ToString(), x);
  179. return _Evaluate(x);
  180. }
  181. private bool _Evaluate(DateTime x)
  182. {
  183. bool result = false;
  184. switch (Operator)
  185. {
  186. case ComparisonOperator.GreaterThanOrEqualTo:
  187. result = (x >= Time);
  188. break;
  189. case ComparisonOperator.GreaterThan:
  190. result = (x > Time);
  191. break;
  192. case ComparisonOperator.LesserThanOrEqualTo:
  193. result = (x <= Time);
  194. break;
  195. case ComparisonOperator.LesserThan:
  196. result = (x < Time);
  197. break;
  198. case ComparisonOperator.EqualTo:
  199. result = (x == Time);
  200. break;
  201. case ComparisonOperator.NotEqualTo:
  202. result = (x != Time);
  203. break;
  204. default:
  205. throw new ArgumentException("Operator");
  206. }
  207. CriterionTrace("TimeCriterion: {0}", result);
  208. return result;
  209. }
  210. }
  211. internal partial class NameCriterion : SelectionCriterion
  212. {
  213. private Regex _re;
  214. private String _regexString;
  215. internal ComparisonOperator Operator;
  216. private string _MatchingFileSpec;
  217. internal virtual string MatchingFileSpec
  218. {
  219. set
  220. {
  221. // workitem 8245
  222. if (Directory.Exists(value))
  223. {
  224. _MatchingFileSpec = "." + Path.DirectorySeparatorChar + value + Path.DirectorySeparatorChar + "*.*";
  225. }
  226. else
  227. {
  228. _MatchingFileSpec = value;
  229. }
  230. _regexString = "^" +
  231. Regex.Escape(_MatchingFileSpec)
  232. .Replace(@"\\\*\.\*", @"\\([^\.]+|.*\.[^\\\.]*)")
  233. .Replace(@"\.\*", @"\.[^\\\.]*")
  234. .Replace(@"\*", @".*")
  235. //.Replace(@"\*", @"[^\\\.]*") // ill-conceived
  236. .Replace(@"\?", @"[^\\\.]")
  237. + "$";
  238. CriterionTrace("NameCriterion regexString({0})", _regexString);
  239. _re = new Regex(_regexString, RegexOptions.IgnoreCase);
  240. }
  241. }
  242. public override String ToString()
  243. {
  244. StringBuilder sb = new StringBuilder();
  245. sb.Append("name ").Append(EnumUtil.GetDescription(Operator))
  246. .Append(" '")
  247. .Append(_MatchingFileSpec)
  248. .Append("'");
  249. return sb.ToString();
  250. }
  251. internal override bool Evaluate(string filename)
  252. {
  253. CriterionTrace("NameCriterion::Evaluate('{0}' pattern[{1}])",
  254. filename, _MatchingFileSpec);
  255. return _Evaluate(filename);
  256. }
  257. private bool _Evaluate(string fullpath)
  258. {
  259. CriterionTrace("NameCriterion::Evaluate({0})", fullpath);
  260. // No slash in the pattern implicitly means recurse, which means compare to
  261. // filename only, not full path.
  262. String f = (_MatchingFileSpec.IndexOf(Path.DirectorySeparatorChar) == -1)
  263. ? System.IO.Path.GetFileName(fullpath)
  264. : fullpath; // compare to fullpath
  265. bool result = _re.IsMatch(f);
  266. if (Operator != ComparisonOperator.EqualTo)
  267. result = !result;
  268. return result;
  269. }
  270. }
  271. internal partial class TypeCriterion : SelectionCriterion
  272. {
  273. private char ObjectType; // 'D' = Directory, 'F' = File
  274. internal ComparisonOperator Operator;
  275. internal string AttributeString
  276. {
  277. get
  278. {
  279. return ObjectType.ToString();
  280. }
  281. set
  282. {
  283. if (value.Length != 1 ||
  284. (value[0]!='D' && value[0]!='F'))
  285. throw new ArgumentException("Specify a single character: either D or F");
  286. ObjectType = value[0];
  287. }
  288. }
  289. public override String ToString()
  290. {
  291. StringBuilder sb = new StringBuilder();
  292. sb.Append("type ").Append(EnumUtil.GetDescription(Operator)).Append(" ").Append(AttributeString);
  293. return sb.ToString();
  294. }
  295. internal override bool Evaluate(string filename)
  296. {
  297. CriterionTrace("TypeCriterion::Evaluate({0})", filename);
  298. bool result = (ObjectType == 'D')
  299. ? Directory.Exists(filename)
  300. : File.Exists(filename);
  301. if (Operator != ComparisonOperator.EqualTo)
  302. result = !result;
  303. return result;
  304. }
  305. }
  306. #if !SILVERLIGHT
  307. internal partial class AttributesCriterion : SelectionCriterion
  308. {
  309. private FileAttributes _Attributes;
  310. internal ComparisonOperator Operator;
  311. internal string AttributeString
  312. {
  313. get
  314. {
  315. string result = "";
  316. if ((_Attributes & FileAttributes.Hidden) != 0)
  317. result += "H";
  318. if ((_Attributes & FileAttributes.System) != 0)
  319. result += "S";
  320. if ((_Attributes & FileAttributes.ReadOnly) != 0)
  321. result += "R";
  322. if ((_Attributes & FileAttributes.Archive) != 0)
  323. result += "A";
  324. if ((_Attributes & FileAttributes.ReparsePoint) != 0)
  325. result += "L";
  326. if ((_Attributes & FileAttributes.NotContentIndexed) != 0)
  327. result += "I";
  328. return result;
  329. }
  330. set
  331. {
  332. _Attributes = FileAttributes.Normal;
  333. foreach (char c in value.ToUpper())
  334. {
  335. switch (c)
  336. {
  337. case 'H':
  338. if ((_Attributes & FileAttributes.Hidden) != 0)
  339. throw new ArgumentException(String.Format("Repeated flag. ({0})", c), "value");
  340. _Attributes |= FileAttributes.Hidden;
  341. break;
  342. case 'R':
  343. if ((_Attributes & FileAttributes.ReadOnly) != 0)
  344. throw new ArgumentException(String.Format("Repeated flag. ({0})", c), "value");
  345. _Attributes |= FileAttributes.ReadOnly;
  346. break;
  347. case 'S':
  348. if ((_Attributes & FileAttributes.System) != 0)
  349. throw new ArgumentException(String.Format("Repeated flag. ({0})", c), "value");
  350. _Attributes |= FileAttributes.System;
  351. break;
  352. case 'A':
  353. if ((_Attributes & FileAttributes.Archive) != 0)
  354. throw new ArgumentException(String.Format("Repeated flag. ({0})", c), "value");
  355. _Attributes |= FileAttributes.Archive;
  356. break;
  357. case 'I':
  358. if ((_Attributes & FileAttributes.NotContentIndexed) != 0)
  359. throw new ArgumentException(String.Format("Repeated flag. ({0})", c), "value");
  360. _Attributes |= FileAttributes.NotContentIndexed;
  361. break;
  362. case 'L':
  363. if ((_Attributes & FileAttributes.ReparsePoint) != 0)
  364. throw new ArgumentException(String.Format("Repeated flag. ({0})", c), "value");
  365. _Attributes |= FileAttributes.ReparsePoint;
  366. break;
  367. default:
  368. throw new ArgumentException(value);
  369. }
  370. }
  371. }
  372. }
  373. public override String ToString()
  374. {
  375. StringBuilder sb = new StringBuilder();
  376. sb.Append("attributes ").Append(EnumUtil.GetDescription(Operator)).Append(" ").Append(AttributeString);
  377. return sb.ToString();
  378. }
  379. private bool _EvaluateOne(FileAttributes fileAttrs, FileAttributes criterionAttrs)
  380. {
  381. bool result = false;
  382. if ((_Attributes & criterionAttrs) == criterionAttrs)
  383. result = ((fileAttrs & criterionAttrs) == criterionAttrs);
  384. else
  385. result = true;
  386. return result;
  387. }
  388. internal override bool Evaluate(string filename)
  389. {
  390. // workitem 10191
  391. if (Directory.Exists(filename))
  392. {
  393. // Directories don't have file attributes, so the result
  394. // of an evaluation is always NO. This gets negated if
  395. // the operator is NotEqualTo.
  396. return (Operator != ComparisonOperator.EqualTo);
  397. }
  398. #if NETCF && !ANDROID
  399. FileAttributes fileAttrs = NetCfFile.GetAttributes(filename);
  400. #else
  401. FileAttributes fileAttrs = System.IO.File.GetAttributes(filename);
  402. #endif
  403. return _Evaluate(fileAttrs);
  404. }
  405. private bool _Evaluate(FileAttributes fileAttrs)
  406. {
  407. bool result = _EvaluateOne(fileAttrs, FileAttributes.Hidden);
  408. if (result)
  409. result = _EvaluateOne(fileAttrs, FileAttributes.System);
  410. if (result)
  411. result = _EvaluateOne(fileAttrs, FileAttributes.ReadOnly);
  412. if (result)
  413. result = _EvaluateOne(fileAttrs, FileAttributes.Archive);
  414. if (result)
  415. result = _EvaluateOne(fileAttrs, FileAttributes.NotContentIndexed);
  416. if (result)
  417. result = _EvaluateOne(fileAttrs, FileAttributes.ReparsePoint);
  418. if (Operator != ComparisonOperator.EqualTo)
  419. result = !result;
  420. return result;
  421. }
  422. }
  423. #endif
  424. internal partial class CompoundCriterion : SelectionCriterion
  425. {
  426. internal LogicalConjunction Conjunction;
  427. internal SelectionCriterion Left;
  428. private SelectionCriterion _Right;
  429. internal SelectionCriterion Right
  430. {
  431. get { return _Right; }
  432. set
  433. {
  434. _Right = value;
  435. if (value == null)
  436. Conjunction = LogicalConjunction.NONE;
  437. else if (Conjunction == LogicalConjunction.NONE)
  438. Conjunction = LogicalConjunction.AND;
  439. }
  440. }
  441. internal override bool Evaluate(string filename)
  442. {
  443. bool result = Left.Evaluate(filename);
  444. switch (Conjunction)
  445. {
  446. case LogicalConjunction.AND:
  447. if (result)
  448. result = Right.Evaluate(filename);
  449. break;
  450. case LogicalConjunction.OR:
  451. if (!result)
  452. result = Right.Evaluate(filename);
  453. break;
  454. case LogicalConjunction.XOR:
  455. result ^= Right.Evaluate(filename);
  456. break;
  457. default:
  458. throw new ArgumentException("Conjunction");
  459. }
  460. return result;
  461. }
  462. public override String ToString()
  463. {
  464. StringBuilder sb = new StringBuilder();
  465. sb.Append("(")
  466. .Append((Left != null) ? Left.ToString() : "null")
  467. .Append(" ")
  468. .Append(Conjunction.ToString())
  469. .Append(" ")
  470. .Append((Right != null) ? Right.ToString() : "null")
  471. .Append(")");
  472. return sb.ToString();
  473. }
  474. }
  475. /// <summary>
  476. /// FileSelector encapsulates logic that selects files from a source - a zip file
  477. /// or the filesystem - based on a set of criteria. This class is used internally
  478. /// by the DotNetZip library, in particular for the AddSelectedFiles() methods.
  479. /// This class can also be used independently of the zip capability in DotNetZip.
  480. /// </summary>
  481. ///
  482. /// <remarks>
  483. ///
  484. /// <para>
  485. /// The FileSelector class is used internally by the ZipFile class for selecting
  486. /// files for inclusion into the ZipFile, when the <see
  487. /// cref="Ionic.Zip.ZipFile.AddSelectedFiles(String,String)"/> method, or one of
  488. /// its overloads, is called. It's also used for the <see
  489. /// cref="Ionic.Zip.ZipFile.ExtractSelectedEntries(String)"/> methods. Typically, an
  490. /// application that creates or manipulates Zip archives will not directly
  491. /// interact with the FileSelector class.
  492. /// </para>
  493. ///
  494. /// <para>
  495. /// Some applications may wish to use the FileSelector class directly, to
  496. /// select files from disk volumes based on a set of criteria, without creating or
  497. /// querying Zip archives. The file selection criteria include: a pattern to
  498. /// match the filename; the last modified, created, or last accessed time of the
  499. /// file; the size of the file; and the attributes of the file.
  500. /// </para>
  501. ///
  502. /// <para>
  503. /// Consult the documentation for <see cref="SelectionCriteria"/>
  504. /// for more information on specifying the selection criteria.
  505. /// </para>
  506. ///
  507. /// </remarks>
  508. public partial class FileSelector
  509. {
  510. internal SelectionCriterion _Criterion;
  511. #if NOTUSED
  512. /// <summary>
  513. /// The default constructor.
  514. /// </summary>
  515. /// <remarks>
  516. /// Typically, applications won't use this constructor. Instead they'll
  517. /// call the constructor that accepts a selectionCriteria string. If you
  518. /// use this constructor, you'll want to set the SelectionCriteria
  519. /// property on the instance before calling SelectFiles().
  520. /// </remarks>
  521. protected FileSelector() { }
  522. #endif
  523. /// <summary>
  524. /// Constructor that allows the caller to specify file selection criteria.
  525. /// </summary>
  526. ///
  527. /// <remarks>
  528. /// <para>
  529. /// This constructor allows the caller to specify a set of criteria for
  530. /// selection of files.
  531. /// </para>
  532. ///
  533. /// <para>
  534. /// See <see cref="FileSelector.SelectionCriteria"/> for a description of
  535. /// the syntax of the selectionCriteria string.
  536. /// </para>
  537. ///
  538. /// <para>
  539. /// By default the FileSelector will traverse NTFS Reparse Points. To
  540. /// change this, use <see cref="FileSelector(String,
  541. /// bool)">FileSelector(String, bool)</see>.
  542. /// </para>
  543. /// </remarks>
  544. ///
  545. /// <param name="selectionCriteria">The criteria for file selection.</param>
  546. public FileSelector(String selectionCriteria)
  547. : this(selectionCriteria, true)
  548. {
  549. }
  550. /// <summary>
  551. /// Constructor that allows the caller to specify file selection criteria.
  552. /// </summary>
  553. ///
  554. /// <remarks>
  555. /// <para>
  556. /// This constructor allows the caller to specify a set of criteria for
  557. /// selection of files.
  558. /// </para>
  559. ///
  560. /// <para>
  561. /// See <see cref="FileSelector.SelectionCriteria"/> for a description of
  562. /// the syntax of the selectionCriteria string.
  563. /// </para>
  564. /// </remarks>
  565. ///
  566. /// <param name="selectionCriteria">The criteria for file selection.</param>
  567. /// <param name="traverseDirectoryReparsePoints">
  568. /// whether to traverse NTFS reparse points (junctions).
  569. /// </param>
  570. public FileSelector(String selectionCriteria, bool traverseDirectoryReparsePoints)
  571. {
  572. if (!String.IsNullOrEmpty(selectionCriteria))
  573. _Criterion = _ParseCriterion(selectionCriteria);
  574. TraverseReparsePoints = traverseDirectoryReparsePoints;
  575. }
  576. /// <summary>
  577. /// The string specifying which files to include when retrieving.
  578. /// </summary>
  579. /// <remarks>
  580. ///
  581. /// <para>
  582. /// Specify the criteria in statements of 3 elements: a noun, an operator,
  583. /// and a value. Consider the string "name != *.doc" . The noun is
  584. /// "name". The operator is "!=", implying "Not Equal". The value is
  585. /// "*.doc". That criterion, in English, says "all files with a name that
  586. /// does not end in the .doc extension."
  587. /// </para>
  588. ///
  589. /// <para>
  590. /// Supported nouns include "name" (or "filename") for the filename;
  591. /// "atime", "mtime", and "ctime" for last access time, last modfied time,
  592. /// and created time of the file, respectively; "attributes" (or "attrs")
  593. /// for the file attributes; "size" (or "length") for the file length
  594. /// (uncompressed); and "type" for the type of object, either a file or a
  595. /// directory. The "attributes", "type", and "name" nouns all support =
  596. /// and != as operators. The "size", "atime", "mtime", and "ctime" nouns
  597. /// support = and !=, and &gt;, &gt;=, &lt;, &lt;= as well. The times are
  598. /// taken to be expressed in local time.
  599. /// </para>
  600. ///
  601. /// <para>
  602. /// Specify values for the file attributes as a string with one or more of
  603. /// the characters H,R,S,A,I,L in any order, implying file attributes of
  604. /// Hidden, ReadOnly, System, Archive, NotContextIndexed, and ReparsePoint
  605. /// (symbolic link) respectively.
  606. /// </para>
  607. ///
  608. /// <para>
  609. /// To specify a time, use YYYY-MM-DD-HH:mm:ss or YYYY/MM/DD-HH:mm:ss as
  610. /// the format. If you omit the HH:mm:ss portion, it is assumed to be
  611. /// 00:00:00 (midnight).
  612. /// </para>
  613. ///
  614. /// <para>
  615. /// The value for a size criterion is expressed in integer quantities of
  616. /// bytes, kilobytes (use k or kb after the number), megabytes (m or mb),
  617. /// or gigabytes (g or gb).
  618. /// </para>
  619. ///
  620. /// <para>
  621. /// The value for a name is a pattern to match against the filename,
  622. /// potentially including wildcards. The pattern follows CMD.exe glob
  623. /// rules: * implies one or more of any character, while ? implies one
  624. /// character. If the name pattern contains any slashes, it is matched to
  625. /// the entire filename, including the path; otherwise, it is matched
  626. /// against only the filename without the path. This means a pattern of
  627. /// "*\*.*" matches all files one directory level deep, while a pattern of
  628. /// "*.*" matches all files in all directories.
  629. /// </para>
  630. ///
  631. /// <para>
  632. /// To specify a name pattern that includes spaces, use single quotes
  633. /// around the pattern. A pattern of "'* *.*'" will match all files that
  634. /// have spaces in the filename. The full criteria string for that would
  635. /// be "name = '* *.*'" .
  636. /// </para>
  637. ///
  638. /// <para>
  639. /// The value for a type criterion is either F (implying a file) or D
  640. /// (implying a directory).
  641. /// </para>
  642. ///
  643. /// <para>
  644. /// Some examples:
  645. /// </para>
  646. ///
  647. /// <list type="table">
  648. /// <listheader>
  649. /// <term>criteria</term>
  650. /// <description>Files retrieved</description>
  651. /// </listheader>
  652. ///
  653. /// <item>
  654. /// <term>name != *.xls </term>
  655. /// <description>any file with an extension that is not .xls
  656. /// </description>
  657. /// </item>
  658. ///
  659. /// <item>
  660. /// <term>name = *.mp3 </term>
  661. /// <description>any file with a .mp3 extension.
  662. /// </description>
  663. /// </item>
  664. ///
  665. /// <item>
  666. /// <term>*.mp3</term>
  667. /// <description>(same as above) any file with a .mp3 extension.
  668. /// </description>
  669. /// </item>
  670. ///
  671. /// <item>
  672. /// <term>attributes = A </term>
  673. /// <description>all files whose attributes include the Archive bit.
  674. /// </description>
  675. /// </item>
  676. ///
  677. /// <item>
  678. /// <term>attributes != H </term>
  679. /// <description>all files whose attributes do not include the Hidden bit.
  680. /// </description>
  681. /// </item>
  682. ///
  683. /// <item>
  684. /// <term>mtime > 2009-01-01</term>
  685. /// <description>all files with a last modified time after January 1st, 2009.
  686. /// </description>
  687. /// </item>
  688. ///
  689. /// <item>
  690. /// <term>ctime > 2009/01/01-03:00:00</term>
  691. /// <description>all files with a created time after 3am (local time),
  692. /// on January 1st, 2009.
  693. /// </description>
  694. /// </item>
  695. ///
  696. /// <item>
  697. /// <term>size > 2gb</term>
  698. /// <description>all files whose uncompressed size is greater than 2gb.
  699. /// </description>
  700. /// </item>
  701. ///
  702. /// <item>
  703. /// <term>type = D</term>
  704. /// <description>all directories in the filesystem. </description>
  705. /// </item>
  706. ///
  707. /// </list>
  708. ///
  709. /// <para>
  710. /// You can combine criteria with the conjunctions AND, OR, and XOR. Using
  711. /// a string like "name = *.txt AND size &gt;= 100k" for the
  712. /// selectionCriteria retrieves entries whose names end in .txt, and whose
  713. /// uncompressed size is greater than or equal to 100 kilobytes.
  714. /// </para>
  715. ///
  716. /// <para>
  717. /// For more complex combinations of criteria, you can use parenthesis to
  718. /// group clauses in the boolean logic. Absent parenthesis, the
  719. /// precedence of the criterion atoms is determined by order of
  720. /// appearance. Unlike the C# language, the AND conjunction does not take
  721. /// precendence over the logical OR. This is important only in strings
  722. /// that contain 3 or more criterion atoms. In other words, "name = *.txt
  723. /// and size &gt; 1000 or attributes = H" implies "((name = *.txt AND size
  724. /// &gt; 1000) OR attributes = H)" while "attributes = H OR name = *.txt
  725. /// and size &gt; 1000" evaluates to "((attributes = H OR name = *.txt)
  726. /// AND size &gt; 1000)". When in doubt, use parenthesis.
  727. /// </para>
  728. ///
  729. /// <para>
  730. /// Using time properties requires some extra care. If you want to
  731. /// retrieve all entries that were last updated on 2009 February 14,
  732. /// specify "mtime &gt;= 2009-02-14 AND mtime &lt; 2009-02-15". Read this
  733. /// to say: all files updated after 12:00am on February 14th, until
  734. /// 12:00am on February 15th. You can use the same bracketing approach to
  735. /// specify any time period - a year, a month, a week, and so on.
  736. /// </para>
  737. ///
  738. /// <para>
  739. /// The syntax allows one special case: if you provide a string with no
  740. /// spaces, it is treated as a pattern to match for the filename.
  741. /// Therefore a string like "*.xls" will be equivalent to specifying "name
  742. /// = *.xls". This "shorthand" notation does not work with compound
  743. /// criteria.
  744. /// </para>
  745. ///
  746. /// <para>
  747. /// There is no logic in this class that insures that the inclusion
  748. /// criteria are internally consistent. For example, it's possible to
  749. /// specify criteria that says the file must have a size of less than 100
  750. /// bytes, as well as a size that is greater than 1000 bytes. Obviously
  751. /// no file will ever satisfy such criteria, but this class does not check
  752. /// for or detect such inconsistencies.
  753. /// </para>
  754. ///
  755. /// </remarks>
  756. ///
  757. /// <exception cref="System.Exception">
  758. /// Thrown in the setter if the value has an invalid syntax.
  759. /// </exception>
  760. public String SelectionCriteria
  761. {
  762. get
  763. {
  764. if (_Criterion == null) return null;
  765. return _Criterion.ToString();
  766. }
  767. set
  768. {
  769. if (value == null) _Criterion = null;
  770. else if (value.Trim() == "") _Criterion = null;
  771. else
  772. _Criterion = _ParseCriterion(value);
  773. }
  774. }
  775. /// <summary>
  776. /// Indicates whether searches will traverse NTFS reparse points, like Junctions.
  777. /// </summary>
  778. public bool TraverseReparsePoints
  779. {
  780. get; set;
  781. }
  782. private enum ParseState
  783. {
  784. Start,
  785. OpenParen,
  786. CriterionDone,
  787. ConjunctionPending,
  788. Whitespace,
  789. }
  790. private static class RegexAssertions
  791. {
  792. public static readonly String PrecededByOddNumberOfSingleQuotes = "(?<=(?:[^']*'[^']*')*'[^']*)";
  793. public static readonly String FollowedByOddNumberOfSingleQuotesAndLineEnd = "(?=[^']*'(?:[^']*'[^']*')*[^']*$)";
  794. public static readonly String PrecededByEvenNumberOfSingleQuotes = "(?<=(?:[^']*'[^']*')*[^']*)";
  795. public static readonly String FollowedByEvenNumberOfSingleQuotesAndLineEnd = "(?=(?:[^']*'[^']*')*[^']*$)";
  796. }
  797. private static string NormalizeCriteriaExpression(string source)
  798. {
  799. // The goal here is to normalize the criterion expression. At output, in
  800. // the transformed criterion string, every significant syntactic element
  801. // - a property element, grouping paren for the boolean logic, operator
  802. // ( = < > != ), conjunction, or property value - will be separated from
  803. // its neighbors by at least one space. Thus,
  804. //
  805. // before after
  806. // -------------------------------------------------------------------
  807. // name=*.txt name = *.txt
  808. // (size>100)AND(name=*.txt) ( size > 100 ) AND ( name = *.txt )
  809. //
  810. // This is relatively straightforward using regular expression
  811. // replacement. This method applies a distinct regex pattern and
  812. // corresponding replacement string for each one of a number of cases:
  813. // an open paren followed by a word; a word followed by a close-paren; a
  814. // pair of open parens; a close paren followed by a word (which should
  815. // then be followed by an open paren). And so on. These patterns and
  816. // replacements are all stored in prPairs. By applying each of these
  817. // regex replacements in turn, we get the transformed string. Easy.
  818. //
  819. // The resulting "normalized" criterion string, is then used as the
  820. // subject that gets parsed, by splitting the string into tokens that
  821. // are separated by spaces. Here, there's a twist. The spaces within
  822. // single-quote delimiters do not delimit distinct tokens. So, this
  823. // normalization method temporarily replaces those spaces with
  824. // ASCII 6 (0x06), a control character which is not a legal
  825. // character in a filename. The parsing logic that happens later will
  826. // revert that change, restoring the original value of the filename
  827. // specification.
  828. //
  829. // To illustrate, for a "before" string of [(size>100)AND(name='Name
  830. // (with Parens).txt')] , the "after" string is [( size > 100 ) AND
  831. // ( name = 'Name\u0006(with\u0006Parens).txt' )].
  832. //
  833. string[][] prPairs =
  834. {
  835. // A. opening double parens - insert a space between them
  836. new string[] { @"([^']*)\(\(([^']+)", "$1( ($2" },
  837. // B. closing double parens - insert a space between
  838. new string[] { @"(.)\)\)", "$1) )" },
  839. // C. single open paren with a following word - insert a space between
  840. new string[] { @"\(([^'\f\n\r\t\v\x85\p{Z}])", "( $1" },
  841. // D. single close paren with a preceding word - insert a space between the two
  842. new string[] { @"(\S)\)", "$1 )" },
  843. // E. close paren at line start?, insert a space before the close paren
  844. // this seems like a degenerate case. I don't recall why it's here.
  845. new string[] { @"^\)", " )" },
  846. // F. a word (likely a conjunction) followed by an open paren - insert a space between
  847. new string[] { @"(\S)\(", "$1 (" },
  848. // G. single close paren followed by word - insert a paren after close paren
  849. new string[] { @"\)([^'\f\n\r\t\v\x85\p{Z}])", ") $1" },
  850. // H. insert space between = and a following single quote
  851. //new string[] { @"(=|!=)('[^']*')", "$1 $2" },
  852. new string[] { @"(=)('[^']*')", "$1 $2" },
  853. // I. insert space between property names and the following operator
  854. //new string[] { @"([^ ])([><(?:!=)=])", "$1 $2" },
  855. new string[] { @"([^ !><])(>|<|!=|=)", "$1 $2" },
  856. // J. insert spaces between operators and the following values
  857. //new string[] { @"([><(?:!=)=])([^ ])", "$1 $2" },
  858. new string[] { @"(>|<|!=|=)([^ =])", "$1 $2" },
  859. // K. replace fwd slash with backslash
  860. new string[] { @"/", "\\" },
  861. };
  862. string interim = source;
  863. for (int i=0; i < prPairs.Length; i++)
  864. {
  865. //char caseIdx = (char)('A' + i);
  866. string pattern = RegexAssertions.PrecededByEvenNumberOfSingleQuotes +
  867. prPairs[i][0] +
  868. RegexAssertions.FollowedByEvenNumberOfSingleQuotesAndLineEnd;
  869. interim = Regex.Replace(interim, pattern, prPairs[i][1]);
  870. }
  871. // match a fwd slash, followed by an odd number of single quotes.
  872. // This matches fwd slashes only inside a pair of single quote delimiters,
  873. // eg, a filename. This must be done as well as the case above, to handle
  874. // filenames specified inside quotes as well as filenames without quotes.
  875. var regexPattern = @"/" +
  876. RegexAssertions.FollowedByOddNumberOfSingleQuotesAndLineEnd;
  877. // replace with backslash
  878. interim = Regex.Replace(interim, regexPattern, "\\");
  879. // match a space, followed by an odd number of single quotes.
  880. // This matches spaces only inside a pair of single quote delimiters.
  881. regexPattern = " " +
  882. RegexAssertions.FollowedByOddNumberOfSingleQuotesAndLineEnd;
  883. // Replace all spaces that appear inside single quotes, with
  884. // ascii 6. This allows a split on spaces to get tokens in
  885. // the expression. The split will not split any filename or
  886. // wildcard that appears within single quotes. After tokenizing, we
  887. // need to replace ascii 6 with ascii 32 to revert the
  888. // spaces within quotes.
  889. return Regex.Replace(interim, regexPattern, "\u0006");
  890. }
  891. private static SelectionCriterion _ParseCriterion(String s)
  892. {
  893. if (s == null) return null;
  894. // inject spaces after open paren and before close paren, etc
  895. s = NormalizeCriteriaExpression(s);
  896. // no spaces in the criteria is shorthand for filename glob
  897. if (s.IndexOf(" ") == -1)
  898. s = "name = " + s;
  899. // split the expression into tokens
  900. string[] tokens = s.Trim().Split(' ', '\t');
  901. if (tokens.Length < 3) throw new ArgumentException(s);
  902. SelectionCriterion current = null;
  903. LogicalConjunction pendingConjunction = LogicalConjunction.NONE;
  904. ParseState state;
  905. var stateStack = new System.Collections.Generic.Stack<ParseState>();
  906. var critStack = new System.Collections.Generic.Stack<SelectionCriterion>();
  907. stateStack.Push(ParseState.Start);
  908. for (int i = 0; i < tokens.Length; i++)
  909. {
  910. string tok1 = tokens[i].ToLower();
  911. switch (tok1)
  912. {
  913. case "and":
  914. case "xor":
  915. case "or":
  916. state = stateStack.Peek();
  917. if (state != ParseState.CriterionDone)
  918. throw new ArgumentException(String.Join(" ", tokens, i, tokens.Length - i));
  919. if (tokens.Length <= i + 3)
  920. throw new ArgumentException(String.Join(" ", tokens, i, tokens.Length - i));
  921. pendingConjunction = (LogicalConjunction)Enum.Parse(typeof(LogicalConjunction), tokens[i].ToUpper(), true);
  922. current = new CompoundCriterion { Left = current, Right = null, Conjunction = pendingConjunction };
  923. stateStack.Push(state);
  924. stateStack.Push(ParseState.ConjunctionPending);
  925. critStack.Push(current);
  926. break;
  927. case "(":
  928. state = stateStack.Peek();
  929. if (state != ParseState.Start && state != ParseState.ConjunctionPending && state != ParseState.OpenParen)
  930. throw new ArgumentException(String.Join(" ", tokens, i, tokens.Length - i));
  931. if (tokens.Length <= i + 4)
  932. throw new ArgumentException(String.Join(" ", tokens, i, tokens.Length - i));
  933. stateStack.Push(ParseState.OpenParen);
  934. break;
  935. case ")":
  936. state = stateStack.Pop();
  937. if (stateStack.Peek() != ParseState.OpenParen)
  938. throw new ArgumentException(String.Join(" ", tokens, i, tokens.Length - i));
  939. stateStack.Pop();
  940. stateStack.Push(ParseState.CriterionDone);
  941. break;
  942. case "atime":
  943. case "ctime":
  944. case "mtime":
  945. if (tokens.Length <= i + 2)
  946. throw new ArgumentException(String.Join(" ", tokens, i, tokens.Length - i));
  947. DateTime t;
  948. try
  949. {
  950. t = DateTime.ParseExact(tokens[i + 2], "yyyy-MM-dd-HH:mm:ss", null);
  951. }
  952. catch (FormatException)
  953. {
  954. try
  955. {
  956. t = DateTime.ParseExact(tokens[i + 2], "yyyy/MM/dd-HH:mm:ss", null);
  957. }
  958. catch (FormatException)
  959. {
  960. try
  961. {
  962. t = DateTime.ParseExact(tokens[i + 2], "yyyy/MM/dd", null);
  963. }
  964. catch (FormatException)
  965. {
  966. try
  967. {
  968. t = DateTime.ParseExact(tokens[i + 2], "MM/dd/yyyy", null);
  969. }
  970. catch (FormatException)
  971. {
  972. t = DateTime.ParseExact(tokens[i + 2], "yyyy-MM-dd", null);
  973. }
  974. }
  975. }
  976. }
  977. t= DateTime.SpecifyKind(t, DateTimeKind.Local).ToUniversalTime();
  978. current = new TimeCriterion
  979. {
  980. Which = (WhichTime)Enum.Parse(typeof(WhichTime), tokens[i], true),
  981. Operator = (ComparisonOperator)EnumUtil.Parse(typeof(ComparisonOperator), tokens[i + 1]),
  982. Time = t
  983. };
  984. i += 2;
  985. stateStack.Push(ParseState.CriterionDone);
  986. break;
  987. case "length":
  988. case "size":
  989. if (tokens.Length <= i + 2)
  990. throw new ArgumentException(String.Join(" ", tokens, i, tokens.Length - i));
  991. Int64 sz = 0;
  992. string v = tokens[i + 2];
  993. if (v.ToUpper().EndsWith("K"))
  994. sz = Int64.Parse(v.Substring(0, v.Length - 1)) * 1024;
  995. else if (v.ToUpper().EndsWith("KB"))
  996. sz = Int64.Parse(v.Substring(0, v.Length - 2)) * 1024;
  997. else if (v.ToUpper().EndsWith("M"))
  998. sz = Int64.Parse(v.Substring(0, v.Length - 1)) * 1024 * 1024;
  999. else if (v.ToUpper().EndsWith("MB"))
  1000. sz = Int64.Parse(v.Substring(0, v.Length - 2)) * 1024 * 1024;
  1001. else if (v.ToUpper().EndsWith("G"))
  1002. sz = Int64.Parse(v.Substring(0, v.Length - 1)) * 1024 * 1024 * 1024;
  1003. else if (v.ToUpper().EndsWith("GB"))
  1004. sz = Int64.Parse(v.Substring(0, v.Length - 2)) * 1024 * 1024 * 1024;
  1005. else sz = Int64.Parse(tokens[i + 2]);
  1006. current = new SizeCriterion
  1007. {
  1008. Size = sz,
  1009. Operator = (ComparisonOperator)EnumUtil.Parse(typeof(ComparisonOperator), tokens[i + 1])
  1010. };
  1011. i += 2;
  1012. stateStack.Push(ParseState.CriterionDone);
  1013. break;
  1014. case "filename":
  1015. case "name":
  1016. {
  1017. if (tokens.Length <= i + 2)
  1018. throw new ArgumentException(String.Join(" ", tokens, i, tokens.Length - i));
  1019. ComparisonOperator c =
  1020. (ComparisonOperator)EnumUtil.Parse(typeof(ComparisonOperator), tokens[i + 1]);
  1021. if (c != ComparisonOperator.NotEqualTo && c != ComparisonOperator.EqualTo)
  1022. throw new ArgumentException(String.Join(" ", tokens, i, tokens.Length - i));
  1023. string m = tokens[i + 2];
  1024. // handle single-quoted filespecs (used to include
  1025. // spaces in filename patterns)
  1026. if (m.StartsWith("'") && m.EndsWith("'"))
  1027. {
  1028. // trim off leading and trailing single quotes and
  1029. // revert the control characters to spaces.
  1030. m = m.Substring(1, m.Length - 2)
  1031. .Replace("\u0006", " ");
  1032. }
  1033. // if (m.StartsWith("'"))
  1034. // m = m.Replace("\u0006", " ");
  1035. //Fix for Unix -> NormalizeCriteriaExpression replaces all slashes with backslashes
  1036. if (Path.DirectorySeparatorChar == '/')
  1037. m = m.Replace('\\', Path.DirectorySeparatorChar);
  1038. current = new NameCriterion
  1039. {
  1040. MatchingFileSpec = m,
  1041. Operator = c
  1042. };
  1043. i += 2;
  1044. stateStack.Push(ParseState.CriterionDone);
  1045. }
  1046. break;
  1047. #if !SILVERLIGHT
  1048. case "attrs":
  1049. case "attributes":
  1050. #endif
  1051. case "type":
  1052. {
  1053. if (tokens.Length <= i + 2)
  1054. throw new ArgumentException(String.Join(" ", tokens, i, tokens.Length - i));
  1055. ComparisonOperator c =
  1056. (ComparisonOperator)EnumUtil.Parse(typeof(ComparisonOperator), tokens[i + 1]);
  1057. if (c != ComparisonOperator.NotEqualTo && c != ComparisonOperator.EqualTo)
  1058. throw new ArgumentException(String.Join(" ", tokens, i, tokens.Length - i));
  1059. #if SILVERLIGHT
  1060. current = (SelectionCriterion) new TypeCriterion
  1061. {
  1062. AttributeString = tokens[i + 2],
  1063. Operator = c
  1064. };
  1065. #else
  1066. current = (tok1 == "type")
  1067. ? (SelectionCriterion) new TypeCriterion
  1068. {
  1069. AttributeString = tokens[i + 2],
  1070. Operator = c
  1071. }
  1072. : (SelectionCriterion) new AttributesCriterion
  1073. {
  1074. AttributeString = tokens[i + 2],
  1075. Operator = c
  1076. };
  1077. #endif
  1078. i += 2;
  1079. stateStack.Push(ParseState.CriterionDone);
  1080. }
  1081. break;
  1082. case "":
  1083. // NOP
  1084. stateStack.Push(ParseState.Whitespace);
  1085. break;
  1086. default:
  1087. throw new ArgumentException("'" + tokens[i] + "'");
  1088. }
  1089. state = stateStack.Peek();
  1090. if (state == ParseState.CriterionDone)
  1091. {
  1092. stateStack.Pop();
  1093. if (stateStack.Peek() == ParseState.ConjunctionPending)
  1094. {
  1095. while (stateStack.Peek() == ParseState.ConjunctionPending)
  1096. {
  1097. var cc = critStack.Pop() as CompoundCriterion;
  1098. cc.Right = current;
  1099. current = cc; // mark the parent as current (walk up the tree)
  1100. stateStack.Pop(); // the conjunction is no longer pending
  1101. state = stateStack.Pop();
  1102. if (state != ParseState.CriterionDone)
  1103. throw new ArgumentException("??");
  1104. }
  1105. }
  1106. else stateStack.Push(ParseState.CriterionDone); // not sure?
  1107. }
  1108. if (state == ParseState.Whitespace)
  1109. stateStack.Pop();
  1110. }
  1111. return current;
  1112. }
  1113. /// <summary>
  1114. /// Returns a string representation of the FileSelector object.
  1115. /// </summary>
  1116. /// <returns>The string representation of the boolean logic statement of the file
  1117. /// selection criteria for this instance. </returns>
  1118. public override String ToString()
  1119. {
  1120. return "FileSelector("+_Criterion.ToString()+")";
  1121. }
  1122. private bool Evaluate(string filename)
  1123. {
  1124. // dinoch - Thu, 11 Feb 2010 18:34
  1125. SelectorTrace("Evaluate({0})", filename);
  1126. bool result = _Criterion.Evaluate(filename);
  1127. return result;
  1128. }
  1129. [System.Diagnostics.Conditional("SelectorTrace")]
  1130. private void SelectorTrace(string format, params object[] args)
  1131. {
  1132. if (_Criterion != null && _Criterion.Verbose)
  1133. System.Console.WriteLine(format, args);
  1134. }
  1135. /// <summary>
  1136. /// Returns the names of the files in the specified directory
  1137. /// that fit the selection criteria specified in the FileSelector.
  1138. /// </summary>
  1139. ///
  1140. /// <remarks>
  1141. /// This is equivalent to calling <see cref="SelectFiles(String, bool)"/>
  1142. /// with recurseDirectories = false.
  1143. /// </remarks>
  1144. ///
  1145. /// <param name="directory">
  1146. /// The name of the directory over which to apply the FileSelector
  1147. /// criteria.
  1148. /// </param>
  1149. ///
  1150. /// <returns>
  1151. /// A collection of strings containing fully-qualified pathnames of files
  1152. /// that match the criteria specified in the FileSelector instance.
  1153. /// </returns>
  1154. public System.Collections.Generic.ICollection<String> SelectFiles(String directory)
  1155. {
  1156. return SelectFiles(directory, false);
  1157. }
  1158. /// <summary>
  1159. /// Returns the names of the files in the specified directory that fit the
  1160. /// selection criteria specified in the FileSelector, optionally recursing
  1161. /// through subdirectories.
  1162. /// </summary>
  1163. ///
  1164. /// <remarks>
  1165. /// This method applies the file selection criteria contained in the
  1166. /// FileSelector to the files contained in the given directory, and
  1167. /// returns the names of files that conform to the criteria.
  1168. /// </remarks>
  1169. ///
  1170. /// <param name="directory">
  1171. /// The name of the directory over which to apply the FileSelector
  1172. /// criteria.
  1173. /// </param>
  1174. ///
  1175. /// <param name="recurseDirectories">
  1176. /// Whether to recurse through subdirectories when applying the file
  1177. /// selection criteria.
  1178. /// </param>
  1179. ///
  1180. /// <returns>
  1181. /// A collection of strings containing fully-qualified pathnames of files
  1182. /// that match the criteria specified in the FileSelector instance.
  1183. /// </returns>
  1184. public System.Collections.ObjectModel.ReadOnlyCollection<String>
  1185. SelectFiles(String directory,
  1186. bool recurseDirectories)
  1187. {
  1188. if (_Criterion == null)
  1189. throw new ArgumentException("SelectionCriteria has not been set");
  1190. var list = new List<String>();
  1191. try
  1192. {
  1193. if (Directory.Exists(directory))
  1194. {
  1195. String[] filenames = Directory.GetFiles(directory);
  1196. // add the files:
  1197. foreach (String filename in filenames)
  1198. {
  1199. if (Evaluate(filename))
  1200. list.Add(filename);
  1201. }
  1202. if (recurseDirectories)
  1203. {
  1204. // add the subdirectories:
  1205. String[] dirnames = Directory.GetDirectories(directory);
  1206. foreach (String dir in dirnames)
  1207. {
  1208. if (this.TraverseReparsePoints
  1209. #if !SILVERLIGHT
  1210. || ((File.GetAttributes(dir) & FileAttributes.ReparsePoint) == 0)
  1211. #endif
  1212. )
  1213. {
  1214. // workitem 10191
  1215. if (Evaluate(dir)) list.Add(dir);
  1216. list.AddRange(this.SelectFiles(dir, recurseDirectories));
  1217. }
  1218. }
  1219. }
  1220. }
  1221. }
  1222. // can get System.UnauthorizedAccessException here
  1223. catch (System.UnauthorizedAccessException)
  1224. {
  1225. }
  1226. catch (System.IO.IOException)
  1227. {
  1228. }
  1229. return list.AsReadOnly();
  1230. }
  1231. }
  1232. /// <summary>
  1233. /// Summary description for EnumUtil.
  1234. /// </summary>
  1235. internal sealed class EnumUtil
  1236. {
  1237. private EnumUtil() { }
  1238. /// <summary>
  1239. /// Returns the value of the DescriptionAttribute if the specified Enum
  1240. /// value has one. If not, returns the ToString() representation of the
  1241. /// Enum value.
  1242. /// </summary>
  1243. /// <param name="value">The Enum to get the description for</param>
  1244. /// <returns></returns>
  1245. internal static string GetDescription(System.Enum value)
  1246. {
  1247. FieldInfo fi = value.GetType().GetField(value.ToString());
  1248. var attributes = (DescriptionAttribute[])fi.GetCustomAttributes(typeof(DescriptionAttribute), false);
  1249. if (attributes.Length > 0)
  1250. return attributes[0].Description;
  1251. else
  1252. return value.ToString();
  1253. }
  1254. /// <summary>
  1255. /// Converts the string representation of the name or numeric value of one
  1256. /// or more enumerated constants to an equivalent enumerated object.
  1257. /// Note: use the DescriptionAttribute on enum values to enable this.
  1258. /// </summary>
  1259. /// <param name="enumType">The System.Type of the enumeration.</param>
  1260. /// <param name="stringRepresentation">
  1261. /// A string containing the name or value to convert.
  1262. /// </param>
  1263. /// <returns></returns>
  1264. internal static object Parse(Type enumType, string stringRepresentation)
  1265. {
  1266. return Parse(enumType, stringRepresentation, false);
  1267. }
  1268. #if SILVERLIGHT
  1269. public static System.Enum[] GetEnumValues(Type type)
  1270. {
  1271. if (!type.IsEnum)
  1272. throw new ArgumentException("not an enum");
  1273. return (
  1274. from field in type.GetFields(BindingFlags.Public | BindingFlags.Static)
  1275. where field.IsLiteral
  1276. select (System.Enum)field.GetValue(null)
  1277. ).ToArray();
  1278. }
  1279. public static string[] GetEnumStrings<T>()
  1280. {
  1281. var type = typeof(T);
  1282. if (!type.IsEnum)
  1283. throw new ArgumentException("not an enum");
  1284. return (
  1285. from field in type.GetFields(BindingFlags.Public | BindingFlags.Static)
  1286. where field.IsLiteral
  1287. select field.Name
  1288. ).ToArray();
  1289. }
  1290. #endif
  1291. /// <summary>
  1292. /// Converts the string representation of the name or numeric value of one
  1293. /// or more enumerated constants to an equivalent enumerated object. A
  1294. /// parameter specified whether the operation is case-sensitive. Note:
  1295. /// use the DescriptionAttribute on enum values to enable this.
  1296. /// </summary>
  1297. /// <param name="enumType">The System.Type of the enumeration.</param>
  1298. /// <param name="stringRepresentation">
  1299. /// A string containing the name or value to convert.
  1300. /// </param>
  1301. /// <param name="ignoreCase">
  1302. /// Whether the operation is case-sensitive or not.</param>
  1303. /// <returns></returns>
  1304. internal static object Parse(Type enumType, string stringRepresentation, bool ignoreCase)
  1305. {
  1306. if (ignoreCase)
  1307. stringRepresentation = stringRepresentation.ToLower();
  1308. #if SILVERLIGHT
  1309. foreach (System.Enum enumVal in GetEnumValues(enumType))
  1310. #else
  1311. foreach (System.Enum enumVal in System.Enum.GetValues(enumType))
  1312. #endif
  1313. {
  1314. string description = GetDescription(enumVal);
  1315. if (ignoreCase)
  1316. description = description.ToLower();
  1317. if (description == stringRepresentation)
  1318. return enumVal;
  1319. }
  1320. return System.Enum.Parse(enumType, stringRepresentation, ignoreCase);
  1321. }
  1322. }
  1323. #if DEMO
  1324. public class DemonstrateFileSelector
  1325. {
  1326. private string _directory;
  1327. private bool _recurse;
  1328. private bool _traverse;
  1329. private bool _verbose;
  1330. private string _selectionCriteria;
  1331. private FileSelector f;
  1332. public DemonstrateFileSelector()
  1333. {
  1334. this._directory = ".";
  1335. this._recurse = true;
  1336. }
  1337. public DemonstrateFileSelector(string[] args) : this()
  1338. {
  1339. for (int i = 0; i < args.Length; i++)
  1340. {
  1341. switch(args[i])
  1342. {
  1343. case"-?":
  1344. Usage();
  1345. Environment.Exit(0);
  1346. break;
  1347. case "-d":
  1348. i++;
  1349. if (args.Length <= i)
  1350. throw new ArgumentException("-directory");
  1351. this._directory = args[i];
  1352. break;
  1353. case "-norecurse":
  1354. this._recurse = false;
  1355. break;
  1356. case "-j-":
  1357. this._traverse = false;
  1358. break;
  1359. case "-j+":
  1360. this._traverse = true;
  1361. break;
  1362. case "-v":
  1363. this._verbose = true;
  1364. break;
  1365. default:
  1366. if (this._selectionCriteria != null)
  1367. throw new ArgumentException(args[i]);
  1368. this._selectionCriteria = args[i];
  1369. break;
  1370. }
  1371. if (this._selectionCriteria != null)
  1372. this.f = new FileSelector(this._selectionCriteria);
  1373. }
  1374. }
  1375. public static void Main(string[] args)
  1376. {
  1377. try
  1378. {
  1379. Console.WriteLine();
  1380. new DemonstrateFileSelector(args).Run();
  1381. }
  1382. catch (Exception exc1)
  1383. {
  1384. Console.WriteLine("Exception: {0}", exc1.ToString());
  1385. Usage();
  1386. }
  1387. }
  1388. public void Run()
  1389. {
  1390. if (this.f == null)
  1391. this.f = new FileSelector("name = *.jpg AND (size > 1000 OR atime < 2009-02-14-01:00:00)");
  1392. this.f.TraverseReparsePoints = _traverse;
  1393. this.f.Verbose = this._verbose;
  1394. Console.WriteLine();
  1395. Console.WriteLine(new String(':', 88));
  1396. Console.WriteLine("Selecting files:\n" + this.f.ToString());
  1397. var files = this.f.SelectFiles(this._directory, this._recurse);
  1398. if (files.Count == 0)
  1399. {
  1400. Console.WriteLine("no files.");
  1401. }
  1402. else
  1403. {
  1404. Console.WriteLine("files: {0}", files.Count);
  1405. foreach (string file in files)
  1406. {
  1407. Console.WriteLine(" " + file);
  1408. }
  1409. }
  1410. }
  1411. public static void Usage()
  1412. {
  1413. Console.WriteLine("FileSelector: select files based on selection criteria.\n");
  1414. Console.WriteLine("Usage:\n FileSelector <selectionCriteria> [options]\n" +
  1415. "\n" +
  1416. " -d <dir> directory to select from (Default .)\n" +
  1417. " -norecurse don't recurse into subdirs\n" +
  1418. " -j- don't traverse junctions\n" +
  1419. " -v verbose output\n");
  1420. }
  1421. }
  1422. #endif
  1423. }