Server.map path not working in asp.net - asp.net

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);

Related

FileStream Object taking forever to push file to browser

I'm using a filestream object to push a report in excel format from our DB, and it works fine for reports that are reasonable in terms the number of rows, however there's one report that has over 15K rows and the site times out after 20 minutes - I know I could increase the timeout, but even 20 minutes is unaccaptable right now. Is there any way to speed things up? Here is my current code:
string path = Server.MapPath(#"~\");
string sourceName = Path.Combine(path, "Demo", "Report_Template", templateName);
string newFileName = Path.Combine(Global.demo_data_directory, #"Reports", #"Demo Download Activity Report.xlsx"); // Path.Combine(path, "Demo_Data", "Reports", Filename + ".xlsx");
string copyresults = Utilities.CopyFile(sourceName, newFileName);
if (copyresults != "Copied file")
{
DemoDAL.ErrorLog("GenerateDownloadActivityReportFile.Page_Load: Copy Error - " + copyresults);
}
else
{
document = SpreadsheetDocument.Open(newFileName, true);
wbPart = document.WorkbookPart;
DataTable datatbl = (DataTable)Session["gvPOC"];
CreateReport(datatbl);
// ADDED THIS *********************************************************************************************************
//wbPart.Workbook.Save();
using (FileStream fsSource = new FileStream(newFileName, FileMode.Open, FileAccess.Read, FileShare.Read, 10240))
{
// Read the source file into a byte array.
byte[] bytes = new byte[fsSource.Length];
int numBytesToRead = (int)fsSource.Length;
int numBytesRead = 0;
while (numBytesToRead > 0)
{
// Read may return anything from 0 to numBytesToRead.
int n = fsSource.Read(bytes, numBytesRead, numBytesToRead);
// Break when the end of the file is reached.
if (n == 0)
break;
numBytesRead += n;
numBytesToRead -= n;
}
numBytesToRead = bytes.Length;
StreamFileToBrowser(newFileName, bytes);
}
File.Delete(newFileName);
}
public void StreamFileToBrowser(string sfilename, byte[] fileBytes)
{
try
{
Response.Clear();
Response.ClearHeaders();
Response.AppendHeader("Content-disposition", String.Format("attachment; filename=\"{0}\"", System.IO.Path.GetFileName(sfilename)));
Response.AppendHeader("Content-Type", "binary/octet-stream");
Response.AppendHeader("Content-length", fileBytes.Length.ToString());
Response.BinaryWrite(fileBytes);
if (Response.IsClientConnected)
Response.Flush();
}
catch (Exception ex)
{
DemoDAL.ErrorLog("StreamFileToBrowser: " + ex.Message);
}
}

Download PDF that I already Created ASP.Net

Long story short,
I want to create button that Print out PDF file to user Computer
So firstly, I create PDF file in server database / file and then I make it downloadable to user.
With this code I can create PDF file in server,
then I searched on how to make it downloadable to user..
So far no luck, most errors said "...is a physical path, but a virtual path was expected."
here's the code
private void cetak_pdf(string s_id, string CompanyCode , string zpath)
{
bool SUCCESS = true;
string sErrMsg = "";
string sFileName = "";
DiskFileDestinationOptions diskOpts = null;
try
{
sFileName = s_id;
diskOpts = new DiskFileDestinationOptions();
diskOpts.DiskFileName = Server.MapPath("~" + "\\pdf\\" + zpath + CompanyCode + "_" + sFileName + ".pdf");
//Response.Write(diskOpts.DiskFileName);Response.End();
// this is the file created E:\GIA_25\pdf\CompanyAddress00000003_003.pdf
rptDoc.ExportOptions.ExportFormatType = ExportFormatType.PortableDocFormat;
rptDoc.ExportOptions.ExportDestinationType = ExportDestinationType.DiskFile;
rptDoc.ExportOptions.DestinationOptions = diskOpts;
rptDoc.Export();
Response.ContentType = "application/pdf";
//Response.AppendHeader("Content-Disposition", "attachment; filename=MyFile.pdf");
Response.TransmitFile(Server.MapPath("E:\\GIA_25\\pdf\\CompanyAddress00000003_003.pdf"));
Response.End();
}
catch (Exception ex)
{
SUCCESS = false;
sErrMsg = ex.Message;
throw new Exception(sErrMsg);
}
}
help please, kinda new in this language
Sorry my fault :( here is the right code for make it downloadable
Response.ContentType = "APPLICATION/OCTET-STREAM";
// String Header = "Attachment; Filename=XMLFile.xml";
String Header = "Attachment; Filename=" + "CompanyAddress" + CompanyCode + "_" + sFileName + ".pdf";
Response.AppendHeader("Content-Disposition", Header);
System.IO.FileInfo Dfile = new System.IO.FileInfo(Server.MapPath("~" + "\\pdf\\" + "CompanyAddress" + CompanyCode + "_" + sFileName + ".pdf"));
Response.WriteFile(Dfile.FullName);

How to download excel file to a specific folder in asp.net

I need to download the excel to the specific folder
Example : D:\email
Now i was able to download the excel file in downloads ....but i need to download in D:\email
this is my code to create excel file :
protected void UploadDataTableToExcel(DataTable dtRecords)
{
string XlsPath = Server.MapPath(#"~/Add_data/test.xls");
string attachment = string.Empty;
if (XlsPath.IndexOf("\\") != -1)
{
string[] strFileName = XlsPath.Split(new char[] { '\\' });
attachment = "attachment; filename=" + strFileName[strFileName.Length - 1];
}
else
attachment = "attachment; filename=" + XlsPath;
try
{
Response.ClearContent();
Response.AddHeader("content-disposition", attachment);
Response.ContentType = "application/vnd.ms-excel";
string tab = string.Empty;
foreach (DataColumn datacol in dtRecords.Columns)
{
Response.Write(tab + datacol.ColumnName);
tab = "\t";
}
Response.Write("\n");
foreach (DataRow dr in dtRecords.Rows)
{
tab = "";
for (int j = 0; j < dtRecords.Columns.Count; j++)
{
Response.Write(tab + Convert.ToString(dr[j]));
tab = "\t";
}
Response.Write("\n");
}
Response.End();
}
catch (Exception ex)
{
//Response.Write(ex.Message);
}
}
you can manually move the file after download using
string sourceFile = #"C:\Users\test\Documents\Downloads\test.xls";
string destinationFile = #"D:\emails\test.xls";
// To move a file or folder to a new location:
System.IO.File.Move(sourceFile, destinationFile);

Why MS Excel does not open properly a CSV file containing Japanese characters in contents?

A CSV file containing Japanese characters (UTF-8 characterset) is created from server-side using ASP.NET.
Code:
public void ExportToCsv_Click(object sender, EventArgs e)
{
try
{
string sContents = string.Empty;
string sTemp;
for (int k = 1; k <= (ObjList.Columns.Count - 1); k++)
{
sContents += ObjList.HeaderRow.Cells[k].Text + ",";
}
sContents += "\r\n";
for (int i = 0; i <= (ObjList.Rows.Count - 1); i++)
{
for (int j = 1; j <= (ObjList.Columns.Count - 1); j++)
{
sTemp = (ObjList.Rows[i].Cells[j].Text.ToString());
if (sTemp == " ")
sTemp = "";
if (j < ObjList.Columns.Count - 1)
sTemp = (sTemp + ",");
sContents += sTemp;
}
sContents += "\r\n";
}
Response.Clear();
Response.ClearHeaders();
Response.ClearContent();
Response.AddHeader("Content-disposition", "attachment; filename=" + "partslist.csv");
Response.ContentType = "application/csv";
Response.Charset = "UTF-8";
Response.ContentEncoding = System.Text.Encoding.UTF8 ;
Response.Write(sContents);
Response.Flush();
Response.End();
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
}
But, when this file is opened in Microsoft Excel 2003, it does not show file contents properly.
How to make excel to open such a file properly.
Help will be appreciated.
Just add \xfeff at the beginning.
Follow this procedure :
Menu -> Data -> GetExternal Data -> From Text
Select your csv using the file dialog
In the text import wizard, step 1, select "65001 : Unicode (UTF-8)" as file origin.
Excel uses SJIS(Shift JIS) as default encoding.
You could try converting UTF-8 to SJIS or creating CSV file with BOM in UTF-8.
I was able to open UTF-8 csv file with BOM.

Downloading file on client side using absolute path .NET

string FilePath = HttpUtility.UrlDecode(Request.QueryString.ToString());
string[] s = FilePath.Split(new char[] { ',' });
string path = s[0];
string FileName = s[1];
String str = HttpContext.Current.Request.Url.AbsolutePath;
System.Web.HttpResponse response = System.Web.HttpContext.Current.Response;
response.ClearContent();
response.Clear();
// response.ContentType = "text/plain";
response.AddHeader("Content-Disposition", "attachment; filename=" + FileName+ ";");
response.TransmitFile(path+FileName);
response.Flush();
response.End();
Above is the code in which i get location of audio file from another page . the audio file is located on a remote machine which is accesible using url e.g. http:\servername\audiofiles\filename.wav . response.Transmit and .WriteFile requires virtual path whereas response.Write() does not download file . How can i give the absolute url instead of virtual path to download file
Found the answer my self from another place :
string FilePath = HttpUtility.UrlDecode(Request.QueryString.ToString());
string[] s = FilePath.Split(new char[] { ',' });
string path = s[0];
string FileName = s[1];
int bytesToRead = 10000;
byte[] buffer = new Byte[bytesToRead];
try
{
HttpWebRequest fileReq = (HttpWebRequest)HttpWebRequest.Create(path+FileName);
HttpWebResponse fileResp = (HttpWebResponse)fileReq.GetResponse();
if (fileReq.ContentLength > 0)
fileResp.ContentLength = fileReq.ContentLength;
stream = fileResp.GetResponseStream();
var resp = HttpContext.Current.Response;
resp.ContentType = "application/octet-stream";
resp.AddHeader("Content-Disposition", "attachment; filename=\"" + FileName + "\"");
resp.AddHeader("Content-Length", fileResp.ContentLength.ToString());
int length;
do
{
if (resp.IsClientConnected)
{
// Read data into the buffer.
length = stream.Read(buffer, 0, bytesToRead);
// and write it out to the response's output stream
resp.OutputStream.Write(buffer, 0, length);
resp.Flush();
//Clear the buffer
buffer = new Byte[bytesToRead];
}
else
{
// cancel the download if client has disconnected
length = -1;
}
} while (length > 0); //Repeat until no data is read
}
finally
{
if (stream != null)
{
//Close the input stream
stream.Close();
}
}
}

Resources