views:

97

answers:

3

My web application wishes to send a file as an attachment to an email. That is quite doable; all I must do is specify the path to the file. But prior to sending the file, the system must create the file- it is a rendered report. It matters not where it is saved, since it will be in an attachment. That being the case, I cannot figure out how to write this file. It works on my localhost but not when I run it on our company's development server. The error message is a 500 one; undescriptive and unknown.

This is part of the event handler that transpires when a user clicks a button to generate a report which will get emailed to her boss:

In this code snippet, ext is some variable three letter file extension and content is content is the returned value of executing Render on a ReportExecutionService object:

var rptPath = HttpContext.Current.Server.MapPath(string.Format("Report.{0}", ext));
//using (var fs = new FileStream(rptPath, FileMode.OpenOrCreate, FileAccess.Write))
using (var fs = File.Create(rptPath))
{
    fs.Write(content, 0, content.Length);
}

...at this point it throws an Exception. I granted the NetworkService account write privileges via right-clicking on the file system of the development server and relaxing permissions to that account. I also relaxed security in IIS 6, which hosts the web application on the development server. What else needs to be done? I merely wish to spit a .pdf file to the root web directory.

A: 

ASP servers generally restrict what folders scripts are allowed to write in. Usually, an ASP application needs to have a dedicated folder configured with write access. Since you are specifying a relative file path to MapPath() without any leading slashes, it is going to return a full file path that is in the same folder as the calling .asp file, which is not likely to be writable within the script.

Remy Lebeau - TeamB
A: 

It works when I right click the folder and grant security permissions full access to the ASPNET account. It didn't work when I granted this to the NetworkService account, but it did when I granted to the ASPNET.

JonathanWolfson
+1  A: 

You could try using the System.IO.Path.GetTempFileName Method. "This creates a uniquely named, zero-byte temporary file on disk and returns the full path of that file." It creates it in the system temp diretcory, so you don't need to worry about clean-up etc.

Dan Diplo
Useful. But the temp directory is not relative to the web application root directory. Isn't it thus inaccessable by the web?
JonathanWolfson
Not necessarily. The asp.net user (typically Network Service user) can access any folder it has permissions granted for, though what these permissions are by default vary depending on your system set-up and the trust level. But I've used this many times without problem from asp.net web sites.
Dan Diplo