views:

33

answers:

2

I have written

List<Attachment> lstAttachment = new List<Attachment>();

            //Check if any error file is present in which case it needs to be send
            if (new FileInfo(Path.Combine(errorFolder, errorFileName)).Exists)
            {
                Attachment unprocessedFile = new Attachment(Path.Combine(errorFolder, errorFileName));
                lstAttachment.Add(unprocessedFile);
            }
            //Check if any processed file is present in which case it needs to be send
           if (new FileInfo(Path.Combine(outputFolder, outputFileName)).Exists)
            {
                Attachment processedFile = new Attachment(Path.Combine(outputFolder, outputFileName));
                lstAttachment.Add(processedFile);
            }

Working fine and is giving the expected output.

Basically I am attaching the file to the list based on whether the file is present or not.

I am looking for any other elegant solution than the one I have written.

Reason: Want to learn differnt ways of representing the same program.

I am using C#3.0

Thanks.

A: 

Is it looks better?

...

var lstAttachment = new List<Attachment>();
string errorPath = Path.Combine(errorFolder, errorFileName);
string outputPath = Path.Combine(outputFolder, outputFileName);

AddAttachmentToCollection(lstAttachment, errorPath);
AddAttachmentToCollection(lstAttachment, outputPath);

...

public static void AddAttachmentToCollection(ICollection<Attachment> collection, string filePath)
{
    if (File.Exists(filePath))
    {
        var attachment = new Attachment(filePath);
        collection.Add(attachment);
    }
}
bniwredyc
A: 

How about a little LINQ?

var filenames = new List<string>() 
{
    Path.Combine(errorFolder, errorFilename),
    Path.Combine(outputFolder, outputFilename)
};
var attachments = filenames.Where(f => File.Exists(f))
                           .Select(f => new Attachment(f));
tzaman