I am facing a strange problem.
I have a web page(Filelibrary.aspx) to download some word/pdf files, I can download the files from local machine and direct link from my local pc. but we have a server and we are usualy accessing the site by login into the server as remote desktop. If we try to download word/pdf files from remort desk top it is downloading the web page "Filelibrary.aspx" instead of the word/pdf. we are using https. I could able to download it before when it was http.
my code:
String strFile = String.Empty;
String[] filename;
strFile = Server.MapPath(ConfigurationManager.AppSettings["TemplatePath"].ToString()) + FileName;
filename = strFile.Split('\\');
Response.Clear();
Response.Buffer = true;// Read the original file from diskFileStream *
Response.AddHeader("Content-Disposition", "attachment; filename=" + filename[filename.Length-1]);
String ext = String.Empty;
if (strFile.IndexOf(".") > 0)
ext = (strFile.Split('.'))[1];
if (ext.ToLower() == "txt")
Response.ContentType = "text/html";
if (ext.ToLower() == "xls")
Response.ContentType = "xls/html";
if (ext.ToLower() == "pdf")
Response.ContentType = "application/pdf";
////combine the path and file name
if (File.Exists(strFile))//open the file and process it
{
FileStream sourceFile = new FileStream(strFile, FileMode.Open, FileAccess.Read);
long FileSize;
FileSize = sourceFile.Length;
Response.AddHeader("Content-Length", FileSize.ToString()); //*
byte[] getContent = new byte[(int)FileSize];
sourceFile.Read(getContent, 0, (int)FileSize);
sourceFile.Close();
Response.BinaryWrite(getContent);
}
Common.UserPageAudit(Session["User"].ToString(), "Download Templates", Session["ROLE"].ToString(), strFile + " Template downloaded");
Can anyone help me to resolve this strange issue..?
Thanks you friends...
at last I found the Problem.
I was not clearing the Header.. I have changed my code as below.
String strFile = String.Empty;
String[] filename;
strFile = Server.MapPath(ConfigurationManager.AppSettings["TemplatePath"].ToString()) + FileName;
filename = strFile.Split('\\');
// Added these two line
HttpContext.Current.Response.Cache.SetNoServerCaching();
Response.ClearHeaders();
Response.Clear();
Response.Buffer = true;// Read the original file from diskFileStream *
Response.AddHeader("Content-Disposition", "attachment; filename=" + filename[filename.Length-1]);
String ext = String.Empty;
if (strFile.IndexOf(".") > 0)
ext = (strFile.Split('.'))[1];
if (ext.ToLower() == "txt")
Response.ContentType = "text/html";
if (ext.ToLower() == "xls")
Response.ContentType = "xls/html";
if (ext.ToLower() == "pdf")
Response.ContentType = "application/pdf";
////combine the path and file name
if (File.Exists(strFile))//open the file and process it
{
FileStream sourceFile = new FileStream(strFile, FileMode.Open, FileAccess.Read);
long FileSize;
FileSize = sourceFile.Length;
Response.AddHeader("Content-Length", FileSize.ToString()); //*
byte[] getContent = new byte[(int)FileSize];
sourceFile.Read(getContent, 0, (int)FileSize);
sourceFile.Close();
Response.BinaryWrite(getContent);
}
Common.UserPageAudit(Session["User"].ToString(), "Download Templates", Session["ROLE"].ToString(), strFile + " Template downloaded");
Related
protected void DownloadFile(object sender, EventArgs e)
{
string param = Request.QueryString["id"];
//int id = int.Parse((sender as LinkButton).CommandArgument);
//byte[] bytes;
string fileName;
SqlCommand cd = DbCon._dbConnection.CreateCommand();
cd.CommandType = CommandType.Text;
cd.CommandText = "select id from student_registration where id = '" + param + "'";
cd.ExecuteNonQuery();
SqlCommand cmd = DbCon._dbConnection.CreateCommand();
cmd.CommandText = "select books_pdf from books where id = '" + param + "'";
// cmd.Parameters.AddWithValue("#Id", param);
String s1 = cmd.ExecuteScalar().ToString();
using (SqlDataReader sdr = cmd.ExecuteReader())
{
sdr.Read();
//bytes = (byte[])sdr["Data"];
//contentType = sdr["ContentType"].ToString();
fileName = sdr["books_pdf"].ToString();
}
Response.Clear();
Response.Buffer = true;
Response.Charset = "/";
Response.Cache.SetCacheability(HttpCacheability.NoCache);
//Response.ContentType = contentType;
Response.ContentType = "application/pdf";
Response.AddHeader("Content-Disposition", "attachment; filename=" + fileName );
//Response.AppendHeader("Content-Disposition", "attachment; filename=" +fileName);
// Response.TransmitFile(Server.MapPath("~/Files/"+ fileName));
// Response.WriteFile(file.FullName);
Response.Flush();
Response.End();
}
This is the code where I have written to download the file. but the result what am getting correct file but '/' is replaced with 'underscore;
My question is how to remove that underscore and add '/' in place of underscore I have attached the image please check that and please help me in finding the solutionenter image description here
enter image description here
image shows the path stored in database and error what I am facing to download
fileName = "../librarian/" + sdr["books_pdf"].ToString();
}
WebClient req = new WebClient();
HttpResponse response = HttpContext.Current.Response;
response.Clear();
response.ClearContent();
response.ClearHeaders();
response.Buffer = true;
response.AddHeader("Content-Disposition", "attachment;filename=\"" + Server.MapPath(fileName) + "\"");
byte[] data = req.DownloadData(Server.MapPath(fileName));
response.BinaryWrite(data);
response.End();
Proper Selection of File was not given later i corrected proper file location than i got proper output
This is my code for downloading text file. But the server.transfer method is not able to resolve that path. It is giving "is not a valid virtual path error"
string filePath = #"D:/BCPResult/Cust_File.t`enter code here`xt";
Response.ContentType = "text/plain";
Response.AppendHeader("content-disposition",
"attachment; filename=" + filePath);
Response.TransmitFile(Server.MapPath(filePath));
Response.End();
Please guide me...
If your file path is not related to server you do not need Server.MapPath.
Also if you run your code in windows, path separator is \, not /.
This code must work:
string filePath = #"D:\BCPResult\Cust_File.txt";
Response.ContentType = "text/plain";
Response.AppendHeader("content-disposition", "attachment; filename=" + filePath);
Response.TransmitFile(filePath);
Response.End();
Use '\' (backslash) instead '/'.
string filePath = #"D:\BCPResult\Cust_File.txt";
or
string filePath = "D:\\BCPResult\\Cust_File.txt";
If You Are trying to access a file from the Remote URL or External URL like (https://www.example.com/)
then you have to Use for the web client like this
string url= "this is the URL of the file from where you want to access the file"
System.Net.WebClient webClient = new System.Net.WebClient();
byte[] bytes = webClient.DownloadData(url);
if (mimetype != null)
{
context.Response.ContentType = mimetype;
}
else
{
context.Response.ContentType = "Application/pdf";
}
context.Response.AppendHeader("Content-Disposition", "attachment; filename=" + fileName);
context.Response.BinaryWrite(bytes);
context.Response.End();
In asp.net MVC I can do something like the following which will open a stream:
Stream strm1 = GenerateReport(Id);
return File(strm1,
"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
"Report_" + reportId.ToString() + ".xlsx");
Notice how I am passing strm1 which is a stream. I can then name it Report_+ ...xlsx like the example above shows.
Is there a similar way to do this with asp.net web forms using c#.
You can use TransmitFile or WriteFile if the file is in your website folder.
string fileName = string.Format("Report_{0}.xlsx", reportId);
Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
Response.AddHeader("Content-Disposition",
string.Format("attachment; filename={0}", fileName));
Response.TransmitFile(fileName);
Response.End();
Stream
If your data is already in Memory, you want this method which writes the response in chunks.
Stream stm1 = GenerateReport(Id);
Int16 bufferSize = 1024;
byte[] buffer = new byte[bufferSize + 1];
Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
Response.AddHeader("Content-Disposition",
string.Format("attachment; filename=\"Report_{0}.xlsx\";", reportId));
Response.BufferOutput = false;
int count = stm1.Read(buffer, 0, bufferSize);
while (count > 0)
{
Response.OutputStream.Write(buffer, 0, count);
count = stm1.Read(buffer, 0, bufferSize);
}
I use this extension to send a stream as a downloadable file:
public static class ToDownloadExtention
{
public static void ToDownload(this Stream stream, string fileName, HttpResponse response)
{
response.Clear();
response.ContentType = "application/octet-stream";
response.AddHeader("Content-Disposition", string.Format("attachment; filename={0}", fileName));
stream.CopyTo(response.OutputStream);
response.End();
}
}
And the usage is:
var stream = new MemoryStream();
stream.ToDownload("someFileName.ext",Response);
Or if you have a stream ready to be written, simply copy it to response stream:
Response.Clear();
Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
Response.AddHeader("Content-Disposition", "attachment; filename={your file name}");
Response.OutputStream.Write(stream, 0, stream.length);
Response.End();
Added same code just for visibility
I am using this code to download a excel file which exist in my solution. I have added a folder FileUpload and added a excel file UploadCWF.xlsx. My code is workin in local host. But not working when I host this to server.I am getting error - Could not find a part of the path. My code -
string filePath = HttpContext.Current.Server.MapPath("~/FileUpload/");
string _DownloadableProductFileName = "UploadCWF.xlsx";
System.IO.FileInfo FileName = new System.IO.FileInfo(filePath + "\\" + _DownloadableProductFileName);
FileStream myFile = new FileStream(filePath + "\\" + _DownloadableProductFileName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
//Reads file as binary values
BinaryReader _BinaryReader = new BinaryReader(myFile);
//Check whether file exists in specified location
if (FileName.Exists)
{
try
{
long startBytes = 0;
string lastUpdateTiemStamp = File.GetLastWriteTimeUtc(filePath).ToString("r");
string _EncodedData = HttpUtility.UrlEncode(_DownloadableProductFileName, Encoding.UTF8) + lastUpdateTiemStamp;
Response.Clear();
Response.Buffer = false;
Response.AddHeader("Accept-Ranges", "bytes");
Response.AppendHeader("ETag", "\"" + _EncodedData + "\"");
Response.AppendHeader("Last-Modified", lastUpdateTiemStamp);
Response.ContentType = "application/octet-stream";
Response.AddHeader("Content-Disposition", "attachment;filename=" + FileName.Name);
Response.AddHeader("Content-Length", (FileName.Length - startBytes).ToString());
Response.AddHeader("Connection", "Keep-Alive");
Response.ContentEncoding = Encoding.UTF8;
//Send data
_BinaryReader.BaseStream.Seek(startBytes, SeekOrigin.Begin);
//Dividing the data in 1024 bytes package
int maxCount = (int)Math.Ceiling((FileName.Length - startBytes + 0.0) / 1024);
//Download in block of 1024 bytes
int i;
for (i = 0; i < maxCount && Response.IsClientConnected; i++)
{
Response.BinaryWrite(_BinaryReader.ReadBytes(1024));
Response.Flush();
}
}
catch (Exception es)
{
throw es;
}
finally
{
Response.End();
_BinaryReader.Close();
myFile.Close();
}
}
else
System.Web.UI.ScriptManager.RegisterStartupScript(this, GetType(),
"FileNotFoundWarning", "alert('File is not available now!')", true);
Please some one help me.
You should first concat filepath and filename then get path using server.mappath.
You should write code like this
string filePath = HttpContext.Current.Server.MapPath("~/FileUpload/UploadCWF.xlsx");
System.IO.FileInfo FileName = new System.IO.FileInfo(filePath);
In my MySql i am having my data field as longblob i would like to get the content in that file so i have written my code as follows
This is what i am doing before inserting
string filePath = Server.MapPath("AchTemplates/genACH.txt");
string filename = Path.GetFileName(filePath);
FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read);
BinaryReader br = new BinaryReader(fs);
Byte[] bytes = br.ReadBytes((Int32)fs.Length);
br.Close();
fs.Close();
string strQuery = "insert into tblFiles(FName,FData) values (#_FName, #_FData)";
MySqlCommand cmd = new MySqlCommand(strQuery);
cmd.Parameters.Add("#_FName", MySqlDbType.VarChar).Value = filename;
cmd.Parameters.Add("#_FData", MySqlDbType.LongBlob).Value = bytes;
InsertUpdateData(cmd);
//Get Data
private void download(DataTable dt)
{
Byte[] bytes = (Byte[])dt.Rows[0]["FData"];
Response.Buffer = true;
Response.Charset = "";
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.ContentType = dt.Rows[0]["ContentType"].ToString();
Response.AddHeader("content-disposition", "attachment;filename="
+ dt.Rows[0]["Name"].ToString());
Response.BinaryWrite(bytes);
Response.Flush();
Response.End();
}
But i am getting the content as system.string[] why it is happening can any one tell
if dt.Rows[0]["FData"] is coming as a string (it is just plain text), use
byte[] bytes = Encoding.UTF8.GetBytes(dt.Rows[0]["FData"]);
If the data is not plain text and binary stored as string (and not base64 encoded), you are in trouble my friend.
UPDATE
According to MySql documentation, it seems you should be using LONGBLOB and not LONGTEXT.