I have a folder in which there are 3-4 pdf files. SO on button click, I want to download PDF files as a ZIP file. For that I have write the below code
string strFilePath = HttpContext.Current.Server.MapPath("~/UploadedFiles/" + SAP_ID + '_' + CANDIDATEID + "\\" + SAP_ID + '_' + CANDIDATEID + ".pdf");
string strDirectory = HttpContext.Current.Server.MapPath("~/UploadedFiles/" + SAP_ID + '_' + CANDIDATEID);
HttpResponseMessage result = new HttpResponseMessage(HttpStatusCode.OK);
if (Directory.Exists(strDirectory))
{
if (File.Exists(strFilePath + ".zip"))
{
var filestream = new System.IO.FileStream(strFilePath + ".zip", System.IO.FileMode.Open, System.IO.FileAccess.Read, System.IO.FileShare.ReadWrite);
filestream.Close();
File.Delete(strFilePath + ".zip");
}
}
// ZipFile.CreateFromDirectory(strDirectory, strDirectory + ".zip");
var stream = new FileStream(strDirectory + ".zip", FileMode.Open);
result.Content = new StreamContent(stream);
result.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment");
result.Content.Headers.ContentDisposition.FileName = Path.GetFileName(strDirectory + ".zip");
result.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
result.Content.Headers.ContentLength = stream.Length;
But on button click the ZIP is not getting downloaded and the browser just loads.
Please help me know what is the cause ?
You may have more luck with the Response.TransmitFile method, here is an example using the address of your zip file -
Response.ContentType = "application/octet-stream";
Response.AppendHeader("Content-Disposition", "attachment; filename=file.zip");
Response.TransmitFile(strFilePath + ".zip");
Response.Flush();
If the zip file isn't getting created you probably need to grant write/modify permissions on your UploadedFiles directory to IIS AppPool\yourAppPoolName .
Related
I have an error with regards to the subject above, basically I am just downloading a file from its path. My download code is this:
string sFile = Request.QueryString["RFBNumber"].ToString();
string sFile2 = Request.QueryString["FolderName"].ToString();
string sFlag = Request.QueryString["Flag"].ToString();
//CreateRFBReport(sFile, sFile2);
//CreateSingleFile(sFile2, sFile);
if (sFlag == "1") {
sFilename = "RFB_" + sFile + "_COLLATED.PDF";
sGlobalFolderName = sFile2;
sFilePath = # "" + sGlobalFolderName + "\\" + sFilename;
WebClient client = new WebClient();
byte[] buff = client.DownloadData(sFilePath);
Response.ContentType = "application/pdf";
Response.AddHeader("content-length", buff.Length.ToString());
Response.BinaryWrite(buff);
}
if (sFlag == "2") {
sFilename = "SOP_" + sFile + "_COLLATED.PDF";
sGlobalFolderName = sFile2;
sFilePath = # "" + sGlobalFolderName + "\\" + sFilename;
WebClient client = new WebClient();
byte[] buff = client.DownloadData(sFilePath);
Response.ContentType = "application/pdf";
Response.AddHeader("content-length", buff.Length.ToString());
Response.BinaryWrite(buff);
}
I have to refresh the page multiple times before I can download the item, however I am having an error on the line byte[] buff = client.DownloadData(sFilePath);
Can anyone help me please? Been searching a way to solve this issue. Thank you in advance.
I am using this code to download a image i.e. I am storing Image name with extension in database and getting it here.
this code throws no error but doesn't download anything. why ?
try {
if (e.CommandName == "Download")
{
string ImgPath = Convert.ToString(r["Attachment"]);
//string ImgName = r["ComplaintDetailID"].ToString() + "-" + r["LetterNo"].ToString() + "-" + DateTime.Now.ToString("ddMMyyyyhhmmss");
//string filePath = ImgName + ".jpg";
string fullFilePath = Server.MapPath("~/SiteImages/CMS/" + ImgPath);
Response.Clear();
Response.ClearHeaders();
Response.ClearContent();
Response.AddHeader("Content-Disposition", "attachment; filename=" + Path.GetFileName(fullFilePath));
Response.ContentType = ContentType;
Response.TransmitFile(fullFilePath); //downloads file
Response.Flush();
//FileInfo file = new FileInfo(fullFilePath);
//file.Delete(); //deletes file after downloading
}
}
catch (Exception ex)
{
ResultLabel.ResultLabelAttributes(ex.Message, ProjectUserControls.Enums.ResultLabel_Color.Red);
}
finally
{
ResultPanel.Controls.Add(ResultLabel);
}
Update:
i tried this but doesn't work.
if (e.CommandName == "Download")
{
string ImgPath = Convert.ToString(r["Attachment"]);
//string ImgName = r["ComplaintDetailID"].ToString() + "-" + r["LetterNo"].ToString() + "-" + DateTime.Now.ToString("ddMMyyyyhhmmss");
//string filePath = ImgName + ".jpg";
MemoryStream m = new MemoryStream();
File.OpenRead(ImgPath).CopyTo(m);
m.WriteTo(Response.OutputStream);
string fullFilePath = Server.MapPath("~/SiteImages/CMS/" + ImgPath);
Response.Clear();
Response.ClearHeaders();
Response.ClearContent();
Response.AddHeader("Content-Disposition", "attachment; filename=" + Path.GetFileName(fullFilePath));
Response.ContentType = ContentType;
Response.TransmitFile(fullFilePath); //downloads file
Response.Flush();
//FileInfo file = new FileInfo(fullFilePath);
//file.Delete(); //deletes file after downloading
}
Create a Stream using following code
MemoryStream m = new MemoryStream();
File.OpenRead(ImgPath ).CopyTo(m);
m.WriteTo(Response.OutputStream);
You're on the right track using TransmitFile. Check this line:
Response.ContentType = ContentType;
It looks like you're setting the ContentType to the page's default.
Try specifying it explicitly:
Response.ContentType = "image/jpeg";
I am working on the schedule control. i need to export the schedule appointments.
from the below code i have created the Test.ics file in temp folder and then copied to new location.
how to do save the file without save temporarily in the temp folder.
Is it possible to store the file in buffer or any temp object instead of storing it in the temp folder?
please find my code snippet below...
string fileName = "Test.ics";
InternetCalendaring.ICSBuilder icsbBuilder = new InternetCalendaring.ICSBuilder(vecVEvents);
sRes = icsbBuilder.ICSBuildProcess();
string FilePath = System.IO.Path.GetTempPath() + fileName;
System.IO.File.WriteAllText(FilePath, sRes);
FileStream MyFileStream = new FileStream(FilePath, FileMode.Open);
long FileSize;
FileSize = MyFileStream.Length;
byte[] Buffer = new byte[(int)FileSize];
MyFileStream.Read(Buffer, 0, (int)MyFileStream.Length);
MyFileStream.Close();
System.Web.HttpContext.Current.Response.AddHeader("content-type", "text/Calendar");
System.Web.HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment;filename=" + fileName);
System.Web.HttpContext.Current.Response.BinaryWrite(Buffer);
System.Web.HttpContext.Current.Response.Clear();
HttpContext.Current.Response.End();
Thanks in advance...
string fileName = "Test.ics";
InternetCalendaring.ICSBuilder icsbBuilder = new InternetCalendaring.ICSBuilder(vecVEvents);
sRes = icsbBuilder.ICSBuildProcess();
byte[] Buffer = Encoding.Unicode.GetBytes(sRes);
System.Web.HttpContext.Current.Response.AddHeader("content-type", "text/Calendar");
System.Web.HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment;filename=" + fileName);
System.Web.HttpContext.Current.Response.BinaryWrite(Buffer);
//System.Web.HttpContext.Current.Response.Clear();
HttpContext.Current.Response.End();
I have to upload file using Ftp protocol on server, and rename uploaded file after uploading.
I can upload it, but don't know how to rename it.
Code looks like this:
FtpWebRequest requestFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri("ftp://" + ftpServer + "/" + "httpdocs/webroot/" + destination + "/" + fileName));
requestFTP.Proxy = null;
requestFTP.Credentials = new NetworkCredential(ftpUser, ftpPassword);
requestFTP.Method = WebRequestMethods.Ftp.UploadFile;
FileStream fStream = fileInfo.OpenRead();
int bufferLength = 2048;
byte[] buffer = new byte[bufferLength];
Stream uploadStream = requestFTP.GetRequestStream();
int contentLength = fStream.Read(buffer, 0, bufferLength);
while (contentLength != 0)
{
uploadStream.Write(buffer, 0, contentLength);
contentLength = fStream.Read(buffer, 0, bufferLength);
}
uploadStream.Close();
fStream.Close();
requestFTP = null;
string newFilename = fileName.Replace(".ftp", "");
requestFTP.Method = WebRequestMethods.Ftp.Rename; // this like makes a problem
requestFTP.RenameTo(newFilename);
Error I'm getting is
Error 2 Non-invocable member 'System.Net.FtpWebRequest.RenameTo'
cannot be used like a method.
RenameTo is a property, not a method. Your code should read:
// requestFTP has been set to null in the previous line
requestFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri("ftp://" + ftpServer + "/" + "httpdocs/webroot/" + destination + "/" + fileName));
requestFTP.Proxy = null;
requestFTP.Credentials = new NetworkCredential(ftpUser, ftpPassword);
string newFilename = fileName.Replace(".ftp", "");
requestFTP.Method = WebRequestMethods.Ftp.Rename;
requestFTP.RenameTo = newFilename;
requestFTP.GetResponse();
Why not just upload it with the correct filename in stead? Change your first line with the filename you actually want.
FtpWebRequest requestFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri("ftp://" + ftpServer + "/" + "httpdocs/webroot/" + destination + "/" + newFileName));
But do open the reading stream from your old filename.
I am actually wondering why when I create a zip file, and I download it just after, I can't open it because it's broken ..
This is the code I am actually using .
string url = ((LinkButton)sender).Tag;
var downloadFileName = string.Format(((LinkButton)sender).ID + ".zip");
System.IO.DirectoryInfo di = new System.IO.DirectoryInfo("C://inetpub//wwwroot//Files//Wireframes//" + url);
using (ZipFile zip = new ZipFile())
{
zip.AddEntry("C://inetpub//wwwroot//Files//Wireframes//" + url, zip.Name);
zip.AddDirectory("C://inetpub//wwwroot//Files//Wireframes//" + url);
zip.Save(downloadFileName);
}
Response.ContentType = "application/zip";
Response.AddHeader("Content-Disposition", "filename=" + downloadFileName);
Also, I am adding directly all the directories with their files inside.
You are not sending the actual data.
Response.ContentType = "application/zip";
Response.AddHeader("Content-Disposition", "filename=" + downloadFileName);
Response.TransmitFile(downloadFileName);
Response.End();