Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Illegal characters in path

Tags:

c#

.net

asp.net

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)
like image 696
timothyclifford Avatar asked Jun 23 '26 04:06

timothyclifford


1 Answers

Attachment(string) accepts a string of the path. StreamReader.ReadToEnd returns the string contents. I suspect you simply want:

Attachment emailAttachement = new Attachment(filename);
message.Attachments.Add(emailAttachement);

Alternatively, use the constructor that accepts a Stream and 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.

like image 190
Marc Gravell Avatar answered Jun 24 '26 17:06

Marc Gravell



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!