Require Editing in the code with exceptional handling

Hi Community,

I require help on the below code

var delimiter = ",";
var allCsv = Directory.EnumerateFiles(@"C:\Users\Documents\UiPath\Files1", "Ansible"+"*.csv", SearchOption.AllDirectories);

string[] header = 
{ 
    "FileName" + delimiter + File.ReadLines(allCsv.First()).First(l => !string.IsNullOrWhiteSpace(l))
};
FileCount =allCsv.Count();
 // Get CSV Data
var mergedData = allCsv.SelectMany(csv => File.ReadLines(csv).SkipWhile(l => string.IsNullOrWhiteSpace(l)).Skip(1).Select(ll => (csv.Contains(delimiter) ? "\""+Path.GetFileName(csv)+"\"" :  Path.GetFileName(csv)) + delimiter + ll)); 

 // skip header of each file
 File.WriteAllLines(@"C:\Users\Documents\UiPath\test1.csv", header.Concat(mergedData));

This is code to merge multiple csv files starting with name Ansible into a single output file. If for example there are 2000 csv files and one of the csv file gives any exception then the process will halt, can you please help in this code with some (try catch/ any other approach) so as it can go to the next file and print or capture the file names with exception in any collection object?

Thanks!

@ppr @Yoichi @ptrobot guyz can you please also have a look, also @ptrobot this code solution was earlier provided by you and @Yoichi .

Could you test with this code:

var delimiter = ",";
var allCsv = Directory.EnumerateFiles(@"C:\Users\Documents\UiPath\Files1", "Ansible"+"*.csv", SearchOption.AllDirectories);

string[] header = 
{ 
    "FileName" + delimiter + File.ReadLines(allCsv.First()).First(l => !string.IsNullOrWhiteSpace(l))
};
FileCount = allCsv.Count();
 // Get CSV Data
var mergedData = allCsv.SelectMany(csv =>
	{
		try {
			return File.ReadLines(csv).SkipWhile(l => string.IsNullOrWhiteSpace(l)).Skip(1).Select(ll => (csv.Contains(delimiter) ? "\""+Path.GetFileName(csv)+"\"" :  Path.GetFileName(csv)) + delimiter + ll);
		} catch (Exception e){
			return new string[0];
		}
	}); 

 // skip header of each file
 File.WriteAllLines(@"C:\Users\Documents\UiPath\test1.csv", header.Concat(mergedData));

Hi @ptrobot,

If I want to catch this exception in uipath how can i do that, also will it create array of string as exception containing all the exceptions encountered?

Thanks!

You can define an internal error list, add errors to the list and then return it to UiPath with an out argument:

// Create internal error list.
var errorList = new List<string>();

...

 // Get CSV Data
var mergedData = allCsv.SelectMany(csv =>
	{
		try {
			return File.ReadLines(csv).SkipWhile(l => string.IsNullOrWhiteSpace(l)).Skip(1).Select(ll => (csv.Contains(delimiter) ? "\""+Path.GetFileName(csv)+"\"" :  Path.GetFileName(csv)) + delimiter + ll);
		} catch (Exception e) {
			errorList.Add(csv + ": " + e.Message); // Add error message to the list
			return new string[0];
		}
	}); 

...

// Return the error list
out_ErrorList = errorList;

OK thanks, I will test and let you know.

Thanks!