Exemplo n.º 1
0
        public static void InitQueryHelper(out ISearchQueryHelper queryHelper, int maxCount)
        {
            // This uses the Microsoft.Search.Interop assembly
            CSearchManager manager = new CSearchManager();

            // SystemIndex catalog is the default catalog in Windows
            ISearchCatalogManager catalogManager = manager.GetCatalog("SystemIndex");

            // Get the ISearchQueryHelper which will help us to translate AQS --> SQL necessary to query the indexer
            queryHelper = catalogManager.GetQueryHelper();

            // Set the number of results we want. Don't set this property if all results are needed.
            queryHelper.QueryMaxResults = maxCount;

            // Set list of columns we want to display, getting the path presently
            queryHelper.QuerySelectColumns = "System.ItemUrl, System.FileName, System.FileAttributes";

            // Set additional query restriction
            queryHelper.QueryWhereRestrictions = "AND scope='file:'";

            // To filter based on title for now
            queryHelper.QueryContentProperties = "System.FileName";

            // Set sorting order
            queryHelper.QuerySorting = "System.DateModified DESC";
        }
        static void doSearch(Object state)
        {
            SearchObjectState sos = (SearchObjectState)state;

            if (sos.SearchString == string.Empty)
            {
                sos.Reset.Set();
                return;
            }
            cHelper = cManager.GetCatalog("SYSTEMINDEX").GetQueryHelper();
            cHelper.QuerySelectColumns = "\"System.ItemNameDisplay\",\"System.ItemPathDisplay\"";

            try
            {
                using (cConnection = new OleDbConnection(
                           cHelper.ConnectionString))
                {
                    cConnection.Open();
                    using (OleDbCommand cmd = new OleDbCommand(
                               cHelper.GenerateSQLFromUserQuery(
                                   sos.SearchString
                                   ),
                               cConnection))
                    {
                        if (cConnection.State == ConnectionState.Open)
                        {
                            using (OleDbDataReader reader = cmd.ExecuteReader())
                            {
                                m_results.Clear();
                                IsWorkingFlag = true;

                                while (!reader.IsClosed && reader.Read())
                                {
                                    m_results.Add(new SearchResult()
                                    {
                                        Name = reader[0].ToString(), Path = reader[1].ToString()
                                    });
                                    if (ToAbortFlag)
                                    {
                                        break;
                                    }
                                }
                                reader.Close();

                                IsWorkingFlag = false;
                            }
                        }
                    }
                    // TODO: Investigate possible RaceOnRCWCleanup exception.
                    cConnection.Close();
                }
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine(ex);
            }

            sos.Reset.Set();
            ToAbortFlag = false;
        }
Exemplo n.º 3
0
        internal bool PathIsIndexed(string path)
        {
            var csm          = new CSearchManager();
            var indexManager = csm.GetCatalog("SystemIndex").GetCrawlScopeManager();

            return(indexManager.IncludedInCrawlScope(path) > 0);
        }
Exemplo n.º 4
0
Arquivo: Form1.cs Projeto: zilo312/aa
        private string GetSql(string aqs)
        {
            CSearchManager        searchManager  = new CSearchManager();
            CSearchCatalogManager catalogManager = searchManager.GetCatalog("SystemIndex");
            CSearchQueryHelper    queryHelper    = catalogManager.GetQueryHelper();

            return(queryHelper.GenerateSQLFromUserQuery(aqs));
        }
Exemplo n.º 5
0
        static void Main(string[] args)
        {
            CSearchManager        manager        = new CSearchManager();
            CSearchCatalogManager catalogManager = manager.GetCatalog("SystemIndex");
            CSearchQueryHelper    queryHelper    = catalogManager.GetQueryHelper();
            string sql = queryHelper.GenerateSQLFromUserQuery("text kind:music");

            Console.WriteLine(sql);
        }
Exemplo n.º 6
0
        internal CSearchQueryHelper CreateQueryHelper()
        {
            // This uses the Microsoft.Search.Interop assembly
            var manager = new CSearchManager();

            // SystemIndex catalog is the default catalog in Windows
            var catalogManager = manager.GetCatalog(SystemIndex);

            // Get the ISearchQueryHelper which will help us to translate AQS --> SQL necessary to query the indexer
            var queryHelper = catalogManager.GetQueryHelper();

            return(queryHelper);
        }
Exemplo n.º 7
0
 internal static bool PathIsIndexed(string path)
 {
     try
     {
         var csm          = new CSearchManager();
         var indexManager = csm.GetCatalog("SystemIndex").GetCrawlScopeManager();
         return(indexManager.IncludedInCrawlScope(path) > 0);
     }
     catch (COMException)
     {
         // Occurs because the Windows Indexing (WSearch) is turned off in services and unable to be used by Explorer plugin
         return(false);
     }
 }
Exemplo n.º 8
0
        public static void RemoveSearchFolder(string strPath)
        {
            if (strPath == null || strPath.Length == 0)
            {
                return;
            }

            CSearchManager           manager            = new CSearchManager();
            CSearchCatalogManager    catalogManager     = manager.GetCatalog("SystemIndex");
            CSearchCrawlScopeManager searchScopeManager = catalogManager.GetCrawlScopeManager();

            searchScopeManager.RevertToDefaultScopes();
            searchScopeManager.RevertToDefaultScopes();
            searchScopeManager.RemoveScopeRule("file:///" + strPath);
        }
Exemplo n.º 9
0
        public void AddPathToSearchIndex(string fullPath)
        {
            Uri path = new Uri(fullPath);

            string indexingPath = path.ToString();

            CSearchManager           csm     = new CSearchManager();
            CSearchCrawlScopeManager manager = csm.GetCatalog("SystemIndex").GetCrawlScopeManager();

            if (manager.IncludedInCrawlScope(indexingPath) == 0)
            {
                manager.AddUserScopeRule(indexingPath, 1, 1, 0);
                manager.SaveAll();
            }
        }
Exemplo n.º 10
0
        public void ReIndexFolder(string strPath)
        {
            if (strPath == null || strPath.Length == 0)
            {
                return;
            }

            String                   searchPath         = "file:///" + strPath.ToLower();
            CSearchManager           manager            = new CSearchManager();
            CSearchCatalogManager    catalogManager     = manager.GetCatalog("SystemIndex");
            CSearchCrawlScopeManager searchScopeManager = catalogManager.GetCrawlScopeManager();

            // create search root
            uint             rootCnt = 0;
            CEnumSearchRoots roots   = searchScopeManager.EnumerateRoots();
            bool             exist   = false;

            do
            {
                CSearchRoot aRoot = new CSearchRoot();

                roots.Next(1, out aRoot, ref rootCnt);
                if (rootCnt != 0)
                {
                    roots.Skip(1);
                    if (aRoot.RootURL == searchPath)
                    {
                        exist = true;
                    }
                }
            } while (rootCnt != 0);

            if (!exist)
            {
                CSearchRoot r = new CSearchRoot();
                r.RootURL = searchPath;
                searchScopeManager.AddRoot(r);
                searchScopeManager.SaveAll();
            }

            searchScopeManager.RevertToDefaultScopes();
            //if (searchScopeManager.IncludedInCrawlScope(searchPath) == 0)
            //{
            searchScopeManager.AddUserScopeRule(searchPath, 1, 1, 0);
            searchScopeManager.SaveAll();
            //}
            catalogManager.ReindexSearchRoot(searchPath);
        }
Exemplo n.º 11
0
        // strPath: c:\folder\subfolder\
        public static void AddSearchFolder(string strPath)
        {
            if (strPath == null || strPath.Length == 0)
            {
                return;
            }

            CSearchManager           manager            = new CSearchManager();
            CSearchCatalogManager    catalogManager     = manager.GetCatalog("SystemIndex");
            CSearchCrawlScopeManager searchScopeManager = catalogManager.GetCrawlScopeManager();

            searchScopeManager.RevertToDefaultScopes();
            if (searchScopeManager.IncludedInCrawlScope("file:///" + strPath) == 0)
            {
                searchScopeManager.AddUserScopeRule("file:///" + strPath, 1, 1, 0);
                searchScopeManager.SaveAll();
            }
        }
Exemplo n.º 12
0
        static void PerformSearch(string libPath, string query)
        {
            string                sqlQuery;
            CSearchManager        srchMgr     = null;
            CSearchCatalogManager srchCatMgr  = null;
            CSearchQueryHelper    queryHelper = null;

            try
            {
                srchMgr     = new CSearchManager();
                srchCatMgr  = srchMgr.GetCatalog("SystemIndex");
                queryHelper = srchCatMgr.GetQueryHelper();
                sqlQuery    = queryHelper.GenerateSQLFromUserQuery(query);
            }
            finally
            {
                if (queryHelper != null)
                {
                    Marshal.FinalReleaseComObject(queryHelper);
                    queryHelper = null;
                }
                if (srchCatMgr != null)
                {
                    Marshal.FinalReleaseComObject(srchCatMgr);
                    srchCatMgr = null;
                }
                if (srchMgr != null)
                {
                    Marshal.FinalReleaseComObject(srchMgr);
                    srchMgr = null;
                }
            }

            Console.Error.WriteLine(sqlQuery);
            Console.Error.WriteLine();

            PerformQuery(libPath, sqlQuery);
        }
Exemplo n.º 13
0
        /// <summary>
        /// Performs a full-text search against the Windows Search Index, by a given file system <paramref name="path"/>
        /// and <paramref name="query"/>. This generates an SQL query that is passed to the Windows Search query processor.
        /// <para>If you know in advance the SQL query you want to pass, use <see cref="PerformQuery"/>.</para>
        /// </summary>
        /// <param name="path">A path in the local file system.</param>
        /// <param name="query">Any full-text search string or search operators accepted by the Windows Search query engine.</param>
        /// <param name="progress">Optionally provide an <see cref="IProgress{T}"/> object to view progress output.</param>
        public static List <SearchResult> PerformSearch(string path, string query, IProgress <string> progress = null)
        {
            string                sqlQuery;
            CSearchManager        srchMgr     = null;
            CSearchCatalogManager srchCatMgr  = null;
            CSearchQueryHelper    queryHelper = null;

            try {
                srchMgr     = new CSearchManager();
                srchCatMgr  = srchMgr.GetCatalog("SystemIndex");
                queryHelper = srchCatMgr.GetQueryHelper();
                sqlQuery    = queryHelper.GenerateSQLFromUserQuery(query);
            }
            finally {
                if (queryHelper != null)
                {
                    Marshal.FinalReleaseComObject(queryHelper);
                    queryHelper = null;
                }

                if (srchCatMgr != null)
                {
                    Marshal.FinalReleaseComObject(srchCatMgr);
                    srchCatMgr = null;
                }

                if (srchMgr != null)
                {
                    Marshal.FinalReleaseComObject(srchMgr);
                    srchMgr = null;
                }
            }

            progress?.Report($"Full query: {sqlQuery}");

            return(PerformQuery(path, sqlQuery, progress));
        }
Exemplo n.º 14
0
 //        /// <summary>
 //        /// Queries the windows search index using simple keyword matching on the FileName and ItemDisplayName.
 //        /// </summary>
 //        private static string SQL_FromSimpleQuery(string keywords)
 //        {
 //            var tostrip = new List<string>
 //            {
 //                "\\",
 //                "/",
 //                ":",
 //                //"*",
 //                "?",
 //                "\"",
 //                "<",
 //                ">",
 //                "|"
 //            };
 //            foreach (var c in tostrip) {
 //                keywords = keywords.Replace(c, "");
 //            }
 //
 //            var select =
 //                string.Format(
 //                    "SELECT TOP {0} System.ItemNameDisplay, System.ItemPathDisplay, System.ItemUrl FROM SystemIndex",
 //                    MaxResults);
 //            var where = "";
 //            if (keywords != "*") {
 //                where =
 //                    string.Format(
 //                        " WHERE (System.Filename LIKE '{0}%' OR CONTAINS (System.ItemNameDisplay, '\"{0}\"'))", keywords);
 //            }
 //
 //            var order = " ORDER BY System.Search.Rank DESC";
 //            var sql = select + where + order;
 //            return sql;
 //        }
 /// <summary>
 /// Queries the windows search index from an AQS query.
 /// </summary>
 /// <remarks><see cref="https://msdn.microsoft.com/en-us/library/aa965711%28v=vs.85%29.aspx"/></remarks>
 private static string SQL_FromAQS(string aqsQuery)
 {
     var manager = new CSearchManager();
     var catalogManager = manager.GetCatalog("SystemIndex");
     var queryHelper = catalogManager.GetQueryHelper();
     queryHelper.QuerySelectColumns =
         "System.ItemNameDisplay, System.ItemPathDisplay, System.ItemUrl, System.Search.Rank";
     queryHelper.QueryWhereRestrictions = "AND scope='file:' AND System.FileAttributes <> ALL BITWISE 2";
     queryHelper.QueryContentProperties = "System.ItemNameDisplay";
     queryHelper.QueryMaxResults = MaxResults;
     queryHelper.QuerySorting = "System.Search.Rank DESC";
     var sql = queryHelper.GenerateSQLFromUserQuery(aqsQuery);
     return sql;
 }
Exemplo n.º 15
0
        //strPath: e.g. c:/disk
        public List <CSearchResultItem> SearchFolder(string strContent, string strPath)
        {
            List <CSearchResultItem> items = new List <CSearchResultItem>();

            if (strContent == null || strContent.Length == 0 || strPath == null || strPath.Length == 0)
            {
                return(items);
            }

            // Thie uses SearchAPI interop assembly
            CSearchManager manager = new CSearchManager();

            // the SystemIndex catalog is the default catalog that windows uses
            CSearchCatalogManager catalogManager = manager.GetCatalog("SystemIndex");

            // get the ISearchQueryHelper which will help us to translate AQS --> SQL necessary to query the indexer
            CSearchQueryHelper queryHelper = catalogManager.GetQueryHelper();

            queryHelper.QueryContentLocale = 2052;
            queryHelper.QueryMaxResults    = 100;
            queryHelper.QueryKeywordLocale = 2052;

            //queryHelper.
            // set the columns we want,只检索文件的名字和内容,不然属性太多了,会出现狗屁不通的结果。
            queryHelper.QuerySelectColumns     = "System.ItemPathDisplay,System.Search.Rank,System.ItemNameDisplay";
            queryHelper.QueryWhereRestrictions = "AND scope='file:" + strPath + "'";
            queryHelper.QuerySorting           = "System.ItemPathDisplay ASC ";
            // queryHelper.s
            queryHelper.QueryContentProperties = "System.Search.Contents,System.ItemNameDisplay";
            string sqlQuery = queryHelper.GenerateSQLFromUserQuery(strContent);

            // --- Perform the query ---
            // create an OleDbConnection object which connects to the indexer provider with the windows application
            System.Data.OleDb.OleDbConnection conn = new OleDbConnection(queryHelper.ConnectionString);

            try
            {
                // open it
                conn.Open();

                // now create an OleDB command object with the query we built above and the connection we just opened.
                OleDbCommand command = new OleDbCommand(sqlQuery, conn);

                // execute the command, which returns the results as an OleDbDataReader.
                OleDbDataReader WDSResults = command.ExecuteReader();

                while (WDSResults.Read())
                {
                    CSearchResultItem aResult = new CSearchResultItem();
                    aResult.FullPath = WDSResults.GetString(0);
                    aResult.Rank     = WDSResults.GetInt32(1);
                    aResult.DispName = WDSResults.GetString(2);
                    items.Add(aResult);
                }

                WDSResults.Close();
            }
            catch (Exception e)
            {
            }
            finally
            {
                conn.Close();
            }

            return(items);
        }
Exemplo n.º 16
0
        static void doSearch(Object state)
        {
            SearchObjectState sos = (SearchObjectState)state;

            if (sos.SearchString == string.Empty)
            {
                m_results.Clear();
                sos.Reset.Set();
                return;
            }
            cHelper = cManager.GetCatalog("SYSTEMINDEX").GetQueryHelper();
            cHelper.QuerySelectColumns = "\"System.ItemNameDisplay\",\"System.ItemUrl\",\"System.ItemPathDisplay\",\"System.DateModified\"";
            cHelper.QueryMaxResults    = MAX_RESULT;
            cHelper.QuerySorting       = "System.Search.Rank desc";

            OleDbConnection cConnection;

            try
            {
                using (cConnection = new OleDbConnection(
                           cHelper.ConnectionString))
                {
                    cConnection.Open();
                    using (OleDbCommand cmd = new OleDbCommand(
                               cHelper.GenerateSQLFromUserQuery(
                                   sos.SearchString
                                   ),
                               cConnection))
                    {
                        if (cConnection.State == ConnectionState.Open)
                        {
                            using (OleDbDataReader reader = cmd.ExecuteReader())
                            {
                                m_results.Clear();
                                IsWorkingFlag = true;

                                while (!reader.IsClosed && reader.Read())
                                {
                                    if (ToAbortFlag)
                                    {
                                        break;
                                    }

                                    SearchResult result = new SearchResult()
                                    {
                                        Name = reader[0].ToString(), Path = reader[1].ToString(), PathDisplay = reader[2].ToString(), DateModified = reader[3].ToString()
                                    };
                                    m_results.Add(result);
                                }

                                IsWorkingFlag = false;
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine(ex);
            }

            sos.Reset.Set();
            ToAbortFlag = false;
        }
Exemplo n.º 17
0
        static void Main(string[] args)
        {
            if (args.Length < 1)
            {
                Console.WriteLine("Usage: ds [file search pattern] [userQuery]");
                Console.WriteLine("[file search pattern] can include '*' and '?' wildcards");
                Console.WriteLine("[userQuery] query to look for inside the document (with operators of OR, AND). Optional.");
                return;
            }

            // First parameter is file name pattern
            string pattern   = args[0];
            string userQuery = " ";

            // Everything else is considered to be a search query
            for (int i = 1; i < args.Length; i++)
            {
                userQuery += args[i] + " ";
            }

            // This uses the Microsoft.Search.Interop assembly
            CSearchManager manager = new CSearchManager();

            // SystemIndex catalog is the default catalog in Windows
            ISearchCatalogManager catalogManager = manager.GetCatalog("SystemIndex");

            // Get the ISearchQueryHelper which will help us to translate AQS --> SQL necessary to query the indexer
            ISearchQueryHelper queryHelper = catalogManager.GetQueryHelper();

            // Set the number of results we want. Don't set this property if all results are needed.
            queryHelper.QueryMaxResults = 10;

            // Set list of columns we want
            queryHelper.QuerySelectColumns = "System.ItemPathDisplay";

            // Set additional query restriction
            queryHelper.QueryWhereRestrictions = "AND scope='file:'";

            // convert file pattern if it is not '*'. Don't create restriction for '*' as it includes all files.
            if (pattern != "*")
            {
                pattern = pattern.Replace("*", "%");
                pattern = pattern.Replace("?", "_");

                if (pattern.Contains("%") || pattern.Contains("_"))
                {
                    queryHelper.QueryWhereRestrictions += " AND System.FileName LIKE '" + pattern + "' ";
                }
                else
                {
                    // if there are no wildcards we can use a contains which is much faster as it uses the index
                    queryHelper.QueryWhereRestrictions += " AND Contains(System.FileName, '" + pattern + "') ";
                }
            }

            // Set sorting order
            queryHelper.QuerySorting = "System.DateModified DESC";

            // Generate SQL from our parameters, converting the userQuery from AQS->WHERE clause
            string sqlQuery = queryHelper.GenerateSQLFromUserQuery(userQuery);

            Console.WriteLine(sqlQuery);

            // --- Perform the query ---
            // create an OleDbConnection object which connects to the indexer provider with the windows application
            using (System.Data.OleDb.OleDbConnection conn = new OleDbConnection(queryHelper.ConnectionString))
            {
                // open the connection
                conn.Open();

                // now create an OleDB command object with the query we built above and the connection we just opened.
                using (OleDbCommand command = new OleDbCommand(sqlQuery, conn))
                {
                    // execute the command, which returns the results as an OleDbDataReader.
                    using (OleDbDataReader WDSResults = command.ExecuteReader())
                    {
                        while (WDSResults.Read())
                        {
                            // col 0 is our path in display format
                            Console.WriteLine("{0}", WDSResults.GetString(0));
                        }
                    }
                }
            }
        }
Exemplo n.º 18
0
        static void Main(string[] args)
        {
            if (args.Length < 1)
            {
                Console.WriteLine("Usage: ds [file search pattern] [userQuery]");
                Console.WriteLine("[file search pattern] can include '*' and '?' wildcards");
                Console.WriteLine("[userQuery] query to look for inside the document (with operators of OR, AND). Optional.");
                return;
            }

            // First parameter is file name pattern
            string pattern = args[0];
            string userQuery = " ";
            // Everything else is considered to be a search query
            for (int i = 1; i < args.Length; i++)
            {
                userQuery += args[i] + " ";
            }

            // This uses the Microsoft.Search.Interop assembly
            CSearchManager manager = new CSearchManager();

            // SystemIndex catalog is the default catalog in Windows
            ISearchCatalogManager catalogManager = manager.GetCatalog("SystemIndex");

            // Get the ISearchQueryHelper which will help us to translate AQS --> SQL necessary to query the indexer
            ISearchQueryHelper queryHelper = catalogManager.GetQueryHelper();

            // Set the number of results we want. Don't set this property if all results are needed.
            queryHelper.QueryMaxResults = 10;

            // Set list of columns we want
            queryHelper.QuerySelectColumns = "System.ItemPathDisplay";

            // Set additional query restriction
            queryHelper.QueryWhereRestrictions = "AND scope='file:'";

            // convert file pattern if it is not '*'. Don't create restriction for '*' as it includes all files.
            if (pattern != "*")
            {
                pattern = pattern.Replace("*", "%");
                pattern = pattern.Replace("?", "_");

                if (pattern.Contains("%") || pattern.Contains("_"))
                {
                    queryHelper.QueryWhereRestrictions += " AND System.FileName LIKE '" + pattern + "' ";
                }
                else
                {
                    // if there are no wildcards we can use a contains which is much faster as it uses the index
                    queryHelper.QueryWhereRestrictions += " AND Contains(System.FileName, '" + pattern + "') ";
                }
            }

            // Set sorting order
            queryHelper.QuerySorting = "System.DateModified DESC";

            // Generate SQL from our parameters, converting the userQuery from AQS->WHERE clause
            string sqlQuery = queryHelper.GenerateSQLFromUserQuery(userQuery);
            Console.WriteLine(sqlQuery);

            // --- Perform the query ---
            // create an OleDbConnection object which connects to the indexer provider with the windows application
            using (System.Data.OleDb.OleDbConnection conn = new OleDbConnection(queryHelper.ConnectionString))
            {
                // open the connection
                conn.Open();

                // now create an OleDB command object with the query we built above and the connection we just opened.
                using (OleDbCommand command = new OleDbCommand(sqlQuery, conn))
                {
                    // execute the command, which returns the results as an OleDbDataReader.
                    using (OleDbDataReader WDSResults = command.ExecuteReader())
                    {
                        while (WDSResults.Read())
                        {
                            // col 0 is our path in display format
                            Console.WriteLine("{0}", WDSResults.GetString(0));
                        }
                    }
                }
            }
        }
Exemplo n.º 19
0
        public void AddPathToSearchIndex(string fullPath)
        {
            Uri path = new Uri(fullPath);

            string indexingPath = path.ToString();

            CSearchManager csm = new CSearchManager();
            CSearchCrawlScopeManager manager = csm.GetCatalog("SystemIndex").GetCrawlScopeManager();

            if (manager.IncludedInCrawlScope(indexingPath) == 0)
            {
                manager.AddUserScopeRule(indexingPath, 1, 1, 0);
                manager.SaveAll();
            }
        }
Exemplo n.º 20
0
        static void doSearch(object state)
        {
            // check if user wants to show file extensions. always show on windows < 8 due to property missing
            string      displayNameColumn = "System.ItemNameDisplayWithoutExtension";
            RegistryKey hideFileExt       = Registry.CurrentUser.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Explorer\\Advanced", false);
            object      hideFileExtValue  = hideFileExt?.GetValue("HideFileExt");

            if ((hideFileExtValue != null && hideFileExtValue.ToString() == "0") || !Interop.Shell.IsWindows8OrBetter)
            {
                displayNameColumn = "System.ItemNameDisplay";
            }

            SearchObjectState sos = (SearchObjectState)state;

            if (sos.SearchString == string.Empty)
            {
                m_results.Clear();
                sos.Reset.Set();
                return;
            }
            cHelper = cManager.GetCatalog("SYSTEMINDEX").GetQueryHelper();
            cHelper.QuerySelectColumns = "\"" + displayNameColumn + "\",\"System.ItemUrl\",\"System.ItemPathDisplay\",\"System.DateModified\"";
            cHelper.QueryMaxResults    = MAX_RESULT;
            cHelper.QuerySorting       = "System.Search.Rank desc";

            OleDbConnection cConnection;

            try
            {
                using (cConnection = new OleDbConnection(
                           cHelper.ConnectionString))
                {
                    cConnection.Open();
                    using (OleDbCommand cmd = new OleDbCommand(
                               cHelper.GenerateSQLFromUserQuery(
                                   sos.SearchString
                                   ),
                               cConnection))
                    {
                        if (cConnection.State == ConnectionState.Open)
                        {
                            using (OleDbDataReader reader = cmd.ExecuteReader())
                            {
                                m_results.Clear();
                                IsWorkingFlag = true;

                                while (!reader.IsClosed && reader.Read())
                                {
                                    if (ToAbortFlag)
                                    {
                                        break;
                                    }

                                    SearchResult result = new SearchResult()
                                    {
                                        Name = reader[0].ToString(), Path = reader[1].ToString(), PathDisplay = reader[2].ToString(), DateModified = reader[3].ToString()
                                    };

                                    if (result.Name.EndsWith(".lnk"))
                                    {
                                        result.Name = result.Name.Substring(0, result.Name.Length - 4); // Windows always hides this regardless of setting, so do it
                                    }
                                    m_results.Add(result);
                                }

                                IsWorkingFlag = false;
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                CairoLogger.Instance.Error("Error in doSearch.", ex);
            }

            sos.Reset.Set();
            ToAbortFlag = false;
        }
Exemplo n.º 21
0
        private IEnumerable <string> FindFiles(string pattern)
        {
            string userQuery = " ";

            // This uses the Microsoft.Search.Interop assembly
            CSearchManager manager = new CSearchManager();

            // SystemIndex catalog is the default catalog in Windows
            ISearchCatalogManager catalogManager = manager.GetCatalog("SystemIndex");

            // Get the ISearchQueryHelper which will help us to translate AQS --> SQL necessary to query the indexer
            ISearchQueryHelper queryHelper = catalogManager.GetQueryHelper();

            // Set the number of results we want. Don't set this property if all results are needed.
            queryHelper.QueryMaxResults = 10;

            // Set list of columns we want
            queryHelper.QuerySelectColumns = "System.ItemUrl";

            // Set additional query restriction
            queryHelper.QueryWhereRestrictions = "AND scope='file:'";

            // convert file pattern if it is not '*'. Don't create restriction for '*' as it includes all files.
            if (pattern != "*")
            {
                pattern = pattern.Replace("*", "%");
                pattern = pattern.Replace("?", "_");

                if (pattern.Contains("%") || pattern.Contains("_"))
                {
                    queryHelper.QueryWhereRestrictions += " AND System.FileName LIKE '" + pattern + "' ";
                }
                else
                {
                    // if there are no wildcards we can use a contains which is much faster as it uses the index
                    queryHelper.QueryWhereRestrictions += " AND Contains(System.FileName, '" + pattern + "') ";
                }
            }

            // Set sorting order
            queryHelper.QuerySorting = "System.DateModified DESC";

            // Generate SQL from our parameters, converting the userQuery from AQS->WHERE clause
            string sqlQuery = queryHelper.GenerateSQLFromUserQuery(userQuery);

            Console.WriteLine(sqlQuery);

            // --- Perform the query ---
            // create an OleDbConnection object which connects to the indexer provider with the windows application
            using (var conn = new OleDbConnection(queryHelper.ConnectionString))
            {
                // open the connection
                conn.Open();

                // now create an OleDB command object with the query we built above and the connection we just opened.
                using (var command = new OleDbCommand(sqlQuery, conn))
                {
                    // execute the command, which returns the results as an OleDbDataReader.
                    using (var results = command.ExecuteReader())
                    {
                        while (results.Read())
                        {
                            var url = results.GetString(0);

                            if (url.StartsWith("file:", StringComparison.InvariantCultureIgnoreCase))
                            {
                                yield return(url.Substring(5).Replace('/', '\\'));
                            }
                        }
                    }
                }
            }
        }