• 如何查询文件夹中文本文件的内容 (LINQ) (C#)


    1. class QueryContents
    2. {
    3. public static void Main()
    4. {
    5. // Modify this path as necessary.
    6. string startFolder = @"c:\program files\Microsoft Visual Studio 9.0\";
    7. // Take a snapshot of the file system.
    8. System.IO.DirectoryInfo dir = new System.IO.DirectoryInfo(startFolder);
    9. // This method assumes that the application has discovery permissions
    10. // for all folders under the specified path.
    11. IEnumerable fileList = dir.GetFiles("*.*", System.IO.SearchOption.AllDirectories);
    12. string searchTerm = @"Visual Studio";
    13. // Search the contents of each file.
    14. // A regular expression created with the RegEx class
    15. // could be used instead of the Contains method.
    16. // queryMatchingFiles is an IEnumerable.
    17. var queryMatchingFiles =
    18. from file in fileList
    19. where file.Extension == ".htm"
    20. let fileText = GetFileText(file.FullName)
    21. where fileText.Contains(searchTerm)
    22. select file.FullName;
    23. // Execute the query.
    24. Console.WriteLine("The term \"{0}\" was found in:", searchTerm);
    25. foreach (string filename in queryMatchingFiles)
    26. {
    27. Console.WriteLine(filename);
    28. }
    29. // Keep the console window open in debug mode.
    30. Console.WriteLine("Press any key to exit");
    31. Console.ReadKey();
    32. }
    33. // Read the contents of the file.
    34. static string GetFileText(string name)
    35. {
    36. string fileContents = String.Empty;
    37. // If the file has been deleted since we took
    38. // the snapshot, ignore it and return the empty string.
    39. if (System.IO.File.Exists(name))
    40. {
    41. fileContents = System.IO.File.ReadAllText(name);
    42. }
    43. return fileContents;
    44. }
    45. }

  • 相关阅读:
    《热题100》字符串、双指针、贪心算法篇
    C++ day1
    git学习入门8——git-revert
    labelme 使用笔记
    QThread Class
    系统学习Python——类(class)代码的编写基础与实例:类可以截获Python运算符
    css3 hover效果
    Mybatis如何批量插入数据?
    java碎碎碎碎碎碎
    【图像压缩】DCT图像无损压缩【含GUI Matlab源码 726期】
  • 原文地址:https://blog.csdn.net/wangyue4/article/details/133933973