How to give an absolute path in sever map method? - c#

I have a folder which contains several PDF files and inserting and viewing all these pdf's are dont by 2 methods. I have to move this folder to place this folder outside of the project file. Therefore I have to use the absolute path. I have tried some coeds in the internet but none of them worked for me.
Following code is in a button clcik event
string directoryPath = #"D:\competion\pdfFolder\";
string svrPath = Server.MapPath(directoryPath);
DataSet ds = new DataSet();
string extension = Path.GetExtension(FileUpload1.FileName);
if ((FileUpload1.HasFile))
{
if (extension == ".pdf")
{
if (grdPolicyDetails.Rows.Count > 0)
{
//Few methods are invoked in the body
}
}
}
There are else parts in the if else statements but i haven't added those codes.

The Server.MapPath method works only with relative paths that are part of the web application structure. If you need to serve PDF files that are located outside, you might need to have some endpoint that will read the file contents on the server and stream it to the client.
For example:
string pdfPath = #"D:\competion\pdfFolder\myfile.pdf";
this.Response.ContentType = "application/pdf";
this.Response.TransmitFile(pdfPath);
this.Response.End();

I created a test project without the folder 'testVirPath'.
In my iis, I added a Virtual Directory that pointed to a folder (testVirPath) on a different drive (other than my project or published drive).
I added the necessary permissions and the same user as my published site on the localhost.
I then added some pdf files to the testVirPath folder and published the project to iis.
Try it.
This will list the pdf files stored on the testVirPath folder.
[Home Controller]
public ActionResult Files()
{
ViewBag.TheFiles = GetFiles(Server.MapPath("/testVirPath/"));
return View();
}
private FileInfo[] GetFiles(string path)
{
DirectoryInfo di = new DirectoryInfo(path);
FileInfo[] files = di.GetFiles();
return files;
}
[Files View]
<div>
#foreach (FileInfo f in #ViewBag.TheFiles)
{
<p>#f.FullName</p>
}
</div>

string directoryPath = Server.MapPath("~/competion/pdfFolder/");
try this !!

Kindly Use these code for pdf upload.
if (fuDoc.HasFile)
{
string ext = "";
string fnm = Path.GetFileName(fuDoc.PostedFile.FileName).ToLower();
ext = Path.GetExtension(fuDoc.PostedFile.FileName).ToLower();
if ((ext != ".doc") & (ext != ".pdf") & (ext != ".docx"))
{
Page.ClientScript.RegisterStartupScript(GetType(), "msgbox", "alert('Please select .doc or .pdf or .docx files only');", true);
fuDoc.Focus();
return;
}
fuDoc.PostedFile.SaveAs(Server.MapPath("~/Upload/Documents/") + fuDoc.FileName);
strDoc = "Upload/Documents/" + fuDoc.FileName;
}

Related

File upload to wwwroot folder in ASP.NET Core

Why is my following codes sometimes work, but sometimes it does't work?
private bool UploadFile(IFormFile ufile, string fname)
{
if (ufile.Length > 0)
{
string fullpath = Path.Combine(_env.WebRootPath, fname);
using (var fileStream = new FileStream(fullpath, FileMode.Create))
{
ufile.CopyToAsync(fileStream);
}
return true;
}
return false;
}
The code did managed to save the picture to a folder which I created under wwwroot, but the picture is not appearing, and even in Visual Studio too.
Is there a way to solve it?
Thanks.
Even when I open up the file explorer of the folder that is storing the pictures, the picture is like is there but not showing any image.
Try as follows. File will be uploaded to images folder under wwwroot folder.
private async Task<bool> UploadFile(IFormFile ufile)
{
if (ufile != null && ufile.Length > 0)
{
var fileName = Path.GetFileName(ufile.FileName);
var filePath = Path.Combine(Directory.GetCurrentDirectory(), #"wwwroot\images", fileName);
using (var fileStream = new FileStream(filePath, FileMode.Create))
{
await ufile.CopyToAsync(fileStream);
}
return true;
}
return false;
}
Had same problem with dot net core, here's what I did:
-Make virtual directory
-Map it to that folder path (inside wwwroot)
-Make your fullpath equals to this VD ; absolute path (can keep it in config file)
-Give write permissions for this folder to iisuser
allow accessing to static files, just add this line in you startup.cs file under Configure method:
app.UseStaticFiles();

How to get the fullname of the file stored in the temp folder in asp.net mvc 5 app?

I have an app written using c# on the top on ASP.NET MVC 5 framework. One of my pages allow a user to upload file to the server. So I use HttpPostedFileBase to upload the file to the server.
However, instead on saving the file to a permanent place, I am hoping be able to extract the fullname of the file and work on it before moving it to a permanent place.
How can I get the temp full-name of the uploaded file?
I tried the following, but the check File.Exists(tempFullname) always fails.
public string GetFullname(HttpPostedFileBase file)
{
string tempFullname = Path.GetTempPath() + file.FileName;
if(File.Exists(tempFullname))
{
return tempFullname;
}
return string.Empty;
}
I also tried the following but temp.Length throw an exception as the file does not exists
public string GetFullname(HttpPostedFileBase file)
{
string temp = new FileInfo(file.FileName);
if(temp.Length > 0)
{
return tempFullname;
}
return string.Empty;
}
To get the full name of need to save the file first, i can't get the location of a file if you don't save it first!
var filePath = Path.Combine(Server.MapPath("<A folder you want>"), file.FileName);
file.Save(filePath);
In this way, filePath is the full path of your file

Application End after saving PDF file in ASP.net

I created one function which get HTML data from session and save that as PDF
for that I used NReco.PdfGenerator
private static string savePdf()
{
if (HttpContext.Current.Session["ReservationPrintHtml"] != null)
{
StringBuilder objStringBuilder = ((StringBuilder)HttpContext.Current.Session["ReservationPrintHtml"]);
string dir = HostingEnvironment.MapPath("~/Pdf");
if (!Directory.Exists(dir))
{
Directory.CreateDirectory(dir);
}
string fileName = "PDF-" + DateTime.Now.ToString("yyyyMMdd-HHMMssffffff") + ".pdf";
string downloadFile = Path.Combine(dir, fileName);
string htmlContent = objStringBuilder.ToString();
byte[] pdfBytes = (new NReco.PdfGenerator.HtmlToPdfConverter()).GeneratePdf(htmlContent);
File.WriteAllBytes(downloadFile, pdfBytes);
return fileName;
}
else
{
return null;
}
}
I'm not facing any issue regarding PDF generation but, After this function execution it directly calls Application_End in Global.asax
I have tried if I get any error in application but Application_Error not execute.
Can anyone have idea what is the problem?
Thank you.
After long search and googling I found that I'm saving files in PDF folder which was included in my project.
So whenever new PDF file was generated AppDomain recycle on folder change run after every 15-20 changes in folders which are included in solution included projects.
so I found solution by adding fcnMode="Disabled" in web.cofig file like below.
<httpRuntime targetFramework="4.5.2" fcnMode="Disabled" />

Upload image worked in local but not work in my hosting

I have a project ASP MVC.In my project i have a form for upload image i used
string path = System.IO.Path.Combine(Server.MapPath("~/images/"));
if (Request.Files.Count > 0 && Request.Files[0].ContentLength > 0)
{
string url = path + home.Image;
if (System.IO.File.Exists(path + home.Image))
{
System.IO.File.Delete(path+home.Image);
}
FileInfo FInfo = new FileInfo(Request.Files[0].FileName);
string filename = "sample";
string ImagePath = path;
Request.Files[0].SaveAs(ImagePath + filename + FInfo.Extension);
}
Above this code in my local system perfectly .I hosted my project in my site.But it now working in my site.
Any one know please help me
Thanks
Please check your path for image folder,
Please check that you have write permission on folder in which you uploading image,
If you do not have permission then go to security tab and allow full control to everyone,

How to download a file in IIS?

I have written two methods such as FileUpLoad() and FileDownLoad() to Upload and Download a single file in my local system.
void FileUpLoad()
{
string hfBrowsePath = fuplGridDocs.PostedFile.FileName; //fuplGridDocs is a fileupload control
if (hfBrowsePath != string.Empty)
{
string destfile = string.Empty;
string FilePath = Path.Combine(#"E:\Documents\");
FileInfo FP = new FileInfo(hfBrowsePath);
hfFileNameAutoGen.Value = PONumber + FP.Extension;
destfile = FilePath + hfFileNameAutoGen.Value; //hfFileNameAutoGen is a hidden field
fuplGridDocs.PostedFile.SaveAs(destfile);
}
}
void FileDownLoad(LinkButton lnkFileName)
{
string filename = lnkFileName.Text;
string FilePath = Path.Combine(#"E:\Documents", filename);
fuplGridDocs.SaveAs(FilePath);
FileInfo fileToDownLoad = new FileInfo(FilePath);
if (fileToDownLoad.Exists)
{
Process.Start(fileToDownLoad.FullName);
}
else
{
lblMessage.Text = "File Not Saved!";
return;
}
}
While running the application before hosting it in IIS, I can upload a file to the desired location and can also retrieve a file from the saved location. But after publishing it in the localhost, I can only Upload a file. I could not download the saved file. There is no exception too. The Uploaded file is saved in the desired location. I don't know why it is not retrieving the file? Why I cant download the file in IIS? I have searched a lot in the internet, but couldn't find the solution. How to solve this? I am using Windows XP and IIS 5.1 version.
How do you expect your Web Application to do a Process.Start when you deploy this site to a server, your just going to be opening pictures on the server, not on the client PC.
I think this will answer your question: http://www.codeproject.com/Articles/74654/File-Download-in-ASP-NET-and-Tracking-the-Status-o
Also the download file is missing a slash after E:\Documents
another option is to add your wildcard to IIS MIME types

Categories

Resources