将文件附件表示到列表中的更好方法(c#3.0)

时间:2010-06-08 06:13:20

标签: c#-3.0 refactoring

我写过

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);
            }

工作正常,并提供预期的输出。

基本上我是根据文件是否存在将文件附加到列表中。

我正在寻找任何其他优雅的解决方案,而不是我所写的。

原因:想要了解表示同一程序的不同方法。

我正在使用C#3.0

感谢。

2 个答案:

答案 0 :(得分:0)

它看起来更好吗?

...

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);
    }
}

答案 1 :(得分:0)

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));