I have a C# console application that sends Excel spreadsheet attachments through email.
I have given the file path in App.config
. While trying to find the file, the code looks at proper location. But when trying to attach the file inside the foreach
statement, it is looking in code's bin
folder.
What am I doing wrong here?
DirectoryInfo dir1 = new DirectoryInfo(ConfigurationManager.AppSettings.Get("FilePath"));
FileInfo[] folderFiles = null;
folderFiles = dir1.GetFiles();
foreach (FileInfo aFile in folderFiles)
{
message.Attachments.Add(new Attachment(aFile.Name));
}
You need to use aFile.FullName
(includes the full path) rather than aFile.Name
(only the filename). If a command is not doing what you expect, you should check the documentation.
Alternatively, you could make it simpler:
string dir1 = ConfigurationManager.AppSettings.Get("FilePath");
foreach(string aFile in Directory.EnumerateFiles(dir1))
{
message.Attachments.Add(new Attachment(aFile));
}
as Directory.EnumerateFiles
simply returns the full filenames and you would have to think about not doing so (e.g. by using Path.GetFileName
) to do otherwise.