将文件从 WWWROOT 附加到电子邮件

Attach A File From WWWROOT To Email

我想将我项目中的 wwwroot 文件夹中的文件附加到我的电子邮件中,但代码不是在 wwwroot 中查找,而是在我的 C:\ -

中查找

我需要更改以下语法中的哪些内容才能提取文件并将其添加为附件?

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

您使用网络根目录生成本地路径,

//...

var fileFullPath = Path.Combine(_hostingEnvironment.WebRootPath, pdfPath, fileName);

但不要使用它

var fs = _hostingEnvironment.WebRootFileProvider.GetFileInfo(Path.Combine(pdfPath, fileName)).CreateReadStream();

//...

使用生成的完整路径。

//...

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

//...