Link to home
Start Free TrialLog in
Avatar of dejandejanovic
dejandejanovic

asked on

Replace Server.MapPath with any path of windows?!

Hello,

I have below code to send email with attachment. Code is working, but only if file is in same root as project files.
But, I need that for example I can choose test.jpg from any path, like D:\test.jpg

Any idea?

Dim NewAttachment As Attachment = New Attachment(Server.MapPath("test.jpg"))
Mail.Attachments.Add(NewAttachment)

Open in new window


Thanks in advance for help.
ASKER CERTIFIED SOLUTION
Avatar of kaufmed
kaufmed
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of dejandejanovic
dejandejanovic

ASKER

Hi,
thank you for help. Code is working.
Now, I have try to replace string "test.jpg" with FileUpload control. I was positive that code will continue working, but get an error.
Dim filename As String = FileUpload1.FileName
        System.IO.Path.IsPathRooted(filename)
        Dim NewAttachment As Attachment = New Attachment(filename)
        Mail.Attachments.Add(NewAttachment)

Open in new window


ERROR:
Could not find file 'C:\Program Files\Common Files\Microsoft Shared\DevServer\10.0\test.jpg'.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.IO.FileNotFoundException: Could not find file 'C:\Program Files\Common Files\Microsoft Shared\DevServer\10.0\test.jpg'.

Thanks...
You haven't included all of the code I posted. The function System.IO.Path.IsPathRooted returns a boolean value indicating whether or not the path being passed to it starts with a directory marker (a slash) or a drive and colon. If the return is false, then you are dealing with a relative path. I used this return value in as a part of an If/Else statement so that if you were dealing with a relative path, then Server.MapPath would be called; otherwise, the full, unaltered path would be passed to your Attachment constructor (since it's an absolute path at that point).

Please review the logic I posted above.
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Got it.
Thank you for help, tips, and support.
Dim fileName As String = Path.GetFileName(FileUpload1.PostedFile.FileName) 
        Dim NewAttachment As New Attachment(FileUpload1.FileContent, fileName) 
        Mail.Attachments.Add(NewAttachment)

Open in new window