none
Catching Exceptions in LINQ Queries RRS feed

  • Question

  • I've written some code to find duplicate files on SharePoint.  However, some of the existing files have paths that are too long.  So, my code throws an exception.  My code is as follows

                System.IO.DirectoryInfo dir = new DirectoryInfo(input);
                IEnumerable<System.IO.FileInfo> fileList = dir.GetFiles("*.*", SearchOption.AllDirectories);
                IEnumerable<IEnumerable<string>> queryDupFiles = from file in fileList
                    group file.FullName by 
                    new MatchingKey { Path = file.FullName  }
                            into fileGroup
                            where fileGroup.Count() > 1
                            select fileGroup;

    How do I catch the exception so that it can be logged without stopping the query?


    Specifically, the error is being thrown when file.FullName is called in the LINQ query.

    • Edited by Newmanb1 Tuesday, August 7, 2012 4:10 PM
    Tuesday, August 7, 2012 3:49 PM

Answers

  • You can write a custom method to process the filename and handle the exceptions there. Then use that method in your LINQ query.

    string GetFilename(FileInfo file)
    {
    	string result = "";
    	try
    	{
    		result = file.FullName;
    	}
    	finally {};
    	return result;
    }
    ...
    var queryDupFiles = from file in fileList
    				let filename = GetFileName(file.FullName)
    				where filename != ""
                    group filename by new MatchingKey { Path = filename  }
    				into fileGroup
    				where fileGroup.Count() > 1
    				select fileGroup;
    This query simply skips those paths that are too long. Perhaps a better solution is to write manually a custom recursive method which traverses a directory and its sub-directories and creates the full-filename itself by concatenating strings.

    List<string> GetAllFiles(string path, string criteria)
    {
    	var dir = new DirectoryInfo(path);
    	var temp = new List<string>();
    	
        var files = dir.GetFiles(criteria);
    	temp.AddRange(files.Select(file => file.FullName));
    	
    	var subdirs = dir.GetDirectories();
    	foreach(var subdir in subdirs)
    		temp.AddRange(GetAllFiles(path + "\\" + subdir.Name, criteria));
    	
    	return temp;
    }
    
    var filenames = GetAllFiles(@"C:\Windows", "*.*");
    var queryDupFiles = from filename in filenames
                        group filename by 
                        new MatchingKey { Path = filename  }
                        into fileGroup
                        where fileGroup.Count() > 1
                        select fileGroup;

    • Marked as answer by Newmanb1 Tuesday, August 7, 2012 7:10 PM
    Tuesday, August 7, 2012 5:50 PM