Trying to upload a word document then attach it to an email which is sent.
Currently getting an IO exception – Illegal characters in path.
Here’s code:
try
{
var fileName = Path.Combine(Server.MapPath("/"), ResumeUpload.FileName);
ResumeUpload.SaveAs(fileName);
using (var resumeContent = new StreamReader(fileName))
{
while (!resumeContent.EndOfStream)
{
var emailAttachement = new Attachment(resumeContent.ReadToEnd());
message.Attachments.Add(emailAttachement);
}
}
var client = new SmtpClient();
client.Send(message);
}
catch(Exception exception)
{
// Handle exception...
}
Currently, the fileName variable is getting set to:
d:\sites\websitename\website.com.au\home\filename.docx
Any ideas why this would break?
Here’s exception
Illegal characters in path. at System.IO.Path.CheckInvalidPathChars(String path)
at System.IO.Path.GetFileName(String path)
at System.IO.FileStream..ctor(String path, FileMode mode, FileAccess access, FileShare share)
at System.Net.Mail.AttachmentBase.SetContentFromFile(String fileName, String mediaType)
at System.Net.Mail.Attachment..ctor(String fileName)
at JobApplication.JobApplication.SendEmail(StringBuilder emailText)
Attachment(string)accepts a string of the path.StreamReader.ReadToEndreturns the string contents. I suspect you simply want:Alternatively, use the constructor that accepts a
Streamand the name/content-type. Note that there are some things to consider if you let people upload arbitrary files into the root of your web-server; I would try to avoid the need to write them to disk (unless you want them for archive), and I wouldn’t be writing them to my web-root.