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 I would also like to retrieve the line number of the match. i.e:
- Search all VB6 fil开发者_Go百科es for reference
- If a reference was found I would like to retrieve the line number on which the reference was located.
Short of opening every file in the directories and iterating through the file and keeping count of which line I am examining for the search term, is there a quicker/easier way of achieving this?
there are a number of tools to do this. I'll list them in edit as I think of them. The first to come to mind is TextPad (menu: search / search in files)
Second tool: UEStudio.
Both of these are paid tools. There are trials, they are quick to install, etc.
Failing that, you could install Cygwin for some Linux style grep functionality.
Q&A to comments
in that case load the file in, split it on "\n", keep a counter, and do the search yourself -- probably with RegEx regular expression.
... there is a cool LINQ Expression here (you just need the where portion): Linq To Text Files
Work with the directory class recursively to catch all files.
http://www.dotnetperls.com/recursively-find-files
You may want to look into the FINDSTR command-line utility: http://technet.microsoft.com/en-us/library/bb490907.aspx
UltraEdit32 is a quicker/easier way of achieving this. I think you don't need to re-create the wheel if there are huge number of wheels..
Here are the functions I used to achieve the desired functionality:
private void FindReferences( List<string> 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:
/// <summary>
/// Determines whether the source string contains the specified value.
/// </summary>
/// <param name="source">The String to search.</param>
/// <param name="toCheck">The search criteria.</param>
/// <param name="comparisonOptions">The string comparison options to use.</param>
/// <returns>
/// <c>true</c> if the source contains the specified value; otherwise, <c>false</c>.
/// </returns>
public static bool Contains( this string source, string value, StringComparison comparisonOptions )
{
return source.IndexOf( value, comparisonOptions ) >= 0;
}
精彩评论