I have an ASP.NET SOAP web service whose web method creates a PDF file, writes it to the "Download" directory of the application, and returns the URL to the user. The code:
MemoryStream mstream = null;
FileStream fs = null;
try
{
mstream = pgPrinter.GenerateMapImage();
byte[] byteArray = mstream.ToArray();
System.Text.StringBuilder sb = new System.Text.StringBuilder(Global.PhysicalDownloadPath);
sb.Append("\\");
string fileName = Guid.NewGuid().ToString() + ".pdf";
sb.Append(fileName);
string filePath = sb.ToString();
fs = new FileStream(filePath, FileMode.CreateNew);
fs.Write(byteArray, 0, byteArray.Length);
string requestURI = this.Context.Request.Url.AbsoluteUri;
string virtPath = requestURI.Remove(requestURI.IndexOf("Service.asmx")) + "Download/" + fileName;
return virtPath;
}
catch (Exception ex)
{
throw new Exception("An error has occurred creating the map pdf.", ex);
}
finally
{
if (mstream != null) mstream.Close();
if (fs != null) fs.Close();
if (pgPrinter != null) pgPrinter.Dispose();
}
Then, in the Global.asax file of the web service, I set the timer in the Application_Start event listener. In the Timer ElapsedEvent listener, I look for any files in the download directory that are older than the timer interval (for testing = 1 min., For deployment ~ 20 min.) And delete them. The code:
private static double deleteTimeInterval;
private static System.Timers.Timer timer;
public static string PhysicalDownloadPath;
void Application_Start(object sender, EventArgs e)
{
deleteTimeInterval = Convert.ToDouble(System.Configuration.ConfigurationManager.AppSettings["FileDeleteInterval"]);
timer = new System.Timers.Timer(deleteTimeInterval);
timer.Enabled = true;
timer.AutoReset = true;
timer.Elapsed += new System.Timers.ElapsedEventHandler(OnTimedEvent);
PhysicalDownloadPath = System.Web.Hosting.HostingEnvironment.ApplicationPhysicalPath + "Download";
}
private static void OnTimedEvent(object source, System.Timers.ElapsedEventArgs e)
{
var folder = new System.IO.DirectoryInfo(PhysicalDownloadPath);
System.IO.FileInfo[] files = folder.GetFiles();
foreach (var file in files)
{
if (file.CreationTime < DateTime.Now.AddMilliseconds(-deleteTimeInterval))
{
string path = PhysicalDownloadPath + "\\" + file.Name;
System.IO.File.Delete(path);
}
}
}
, . - inetpub\wwwroot (Windows 7, IIS7), . , IIS , wwwroot. , , IIS - . - , . , , wwwroot? , , .