Reputation: 4721
I m storing the excel files in a folder based on SYSDATE
(current date). Now I dont want to download all the files from the folder.
But I want to download the latest file from the folder which is based on time. Here is what my code look likes. As currently I was downloading all the excel files from the folder in a zip.
else if (strSelectedReportType == "RCOMReports")
{
string strReportFile = ConfigurationManager.AppSettings["RCOMReports"].ToString();
string strFilePath = ConfigurationManager.AppSettings["ReportDirectory"].ToString() + "\\" + DateTime.Now.ToString("dd-MM-yyyy");
using (ZipFile zip = new ZipFile())
{
zip.AlternateEncodingUsage = ZipOption.AsNecessary;
if (Directory.Exists(strFilePath))
{
DirectoryInfo di = new DirectoryInfo(strFilePath);
FileInfo[] FileInfo = di.GetFiles();
if (FileInfo.Length > 0)
{
foreach (FileInfo item in FileInfo)
{
zip.AddFile(item.FullName, "Files");
}
}
MemoryStream ms = new MemoryStream();
Stream Objstream = new MemoryStream(ms.ToArray());
Objstream.Seek(0, SeekOrigin.Begin);
zip.AddEntry(strReportFile, Objstream);
HttpContext.Current.Response.Clear();
HttpContext.Current.Response.BufferOutput = false;
string zipName = String.Format("Zip_{0}.zip", strReportFile);
HttpContext.Current.Response.ContentType = "application/zip";
HttpContext.Current.Response.AddHeader("content-disposition", "attachment; filename=" + zipName);
zip.Save(HttpContext.Current.Response.OutputStream);
HttpContext.Current.Response.End();
}
else
{
ScriptManager.RegisterStartupScript(Page, Page.GetType(), "Alert", "alert('No Reports as on today's date..!!');", true);
}
}
}
Now I dont want Zip also
Upvotes: 0
Views: 332
Reputation: 2498
Find last file and download it.
var directory = new DirectoryInfo(ConfigurationManager.AppSettings["ReportDirectory"]);
// the latest excel file
var file = directory.GetFiles().OrderByDescending(c => c.LastWriteTime).FirstOrDefault();
if (file == null)
{
return;
}
var content = File.ReadAllBytes(file.FullName);
HttpContext.Current.Response.ContentType = "text/csv";
HttpContext.Current.Response.AddHeader("content-disposition", "attachment; filename=" + file.Name + ".xlsx");
HttpContext.Current.Response.BufferOutput = true;
HttpContext.Current.Response.OutputStream.Write(content, 0, content.Length);
HttpContext.Current.Response.End();
Upvotes: 1