Reputation: 564
I want to attach a file from my wwwroot folder in my project to my email, but instead of looking in wwwroot, the code is looking on my C:\ -
What do I need to change in the below syntax so the file is picked up and added as an attachment?
var listAtta = new List<FileAttachment>();
emailProducts.Select(o => o.tp).ToList().ForEach(o =>
{
var fileBytes = FileToByteArray(o.ProductPdf);
if (fileBytes != null && fileBytes.Count() > 0)
{
listAtta.Add(new FileAttachment
{
FileData = fileBytes,
FileName = o.ProductPdf
});
}
});
private byte[] FileToByteArray(string fileName)
{
byte[] _Buffer = null;
var pdfPath = context.Tblsettings.FirstOrDefault().Pdffolder;
try
{
var fileFullPath = Path.Combine(_hostingEnvironment.WebRootPath, pdfPath, fileName);
var fs = _hostingEnvironment.WebRootFileProvider.GetFileInfo(Path.Combine(pdfPath, fileName)).CreateReadStream();
long _TotalBytes = new FileInfo(Path.Combine(pdfPath, fileName)).Length;
// attach filestream to binary reader
BinaryReader _BinaryReader = new System.IO.BinaryReader(fs);
// read entire file into buffer
_Buffer = _BinaryReader.ReadBytes((int)_TotalBytes);
_BinaryReader.Close();
}
catch (Exception _Exception)
{
// Error
Console.WriteLine("Exception caught in process: {0}", _Exception.ToString());
}
return _Buffer;
}
Upvotes: 0
Views: 342
Reputation: 247333
You generate a local path using the web root,
//...
var fileFullPath = Path.Combine(_hostingEnvironment.WebRootPath, pdfPath, fileName);
yet don't use it
var fs = _hostingEnvironment.WebRootFileProvider.GetFileInfo(Path.Combine(pdfPath, fileName)).CreateReadStream();
//...
Use the full path generated through out.
//...
var fileFullPath = Path.Combine(_hostingEnvironment.WebRootPath, pdfPath, fileName);
var fs = _hostingEnvironment.WebRootFileProvider.GetFileInfo(fileFullPath).CreateReadStream();
long _TotalBytes = fs.Length;
// attach filestream to binary reader
using(BinaryReader _BinaryReader = new System.IO.BinaryReader(fs)) {
// read entire file into buffer
_Buffer = _BinaryReader.ReadBytes((int)_TotalBytes);
}
//...
Upvotes: 1