Find Text in Files and retrieve the line number

前端 未结 4 1173
悲&欢浪女
悲&欢浪女 2021-01-14 09:38

I am trying to (programatically) find references to a specific string i.e. \'LOCK_ID\' within a large number of VB6 files. To help people navigate directly to the reference

4条回答
  •  终归单人心
    2021-01-14 10:01

    Here are the functions I used to achieve the desired functionality:

    private void FindReferences( List output, string searchPath, string searchString )
    {
        if ( Directory.Exists( searchPath ) )
        {                                                                
            string[] files = Directory.GetFiles( searchPath, "*.*", SearchOption.AllDirectories );
            string line;
    
            // Loop through all the files in the specified directory & in all sub-directories
            foreach ( string file in files )
            {
                using ( StreamReader reader = new StreamReader( file ) )
                {
                    int lineNumber = 1;
                    while ( ( line = reader.ReadLine() ) != null )
                    {
                        if ( line.Contains( searchString, StringComparison.OrdinalIgnoreCase ) )
                        {
                            output.Add( string.Format( "{0}:{1}", file, lineNumber ) );
                        }
    
                        lineNumber++;
                    }
                }                   
            }
        }
    }
    

    Helper class:

    /// 
    /// Determines whether the source string contains the specified value.
    /// 
    /// The String to search.
    /// The search criteria.
    /// The string comparison options to use.
    /// 
    ///   true if the source contains the specified value; otherwise, false.
    /// 
    public static bool Contains( this string source, string value, StringComparison comparisonOptions )
    {
        return source.IndexOf( value, comparisonOptions ) >= 0;
    }
    

提交回复
热议问题