How to download a file in IIS? - c#

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

Related

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

How to give an absolute path in sever map method?

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

How to create and save a temporary file on Microsoft Azure virtual server

I am using a free MS Azure virtual webserver for my site.
On my dev machine I can successfully create a CSV file, save it to a relative temp directory, and then download it to the browser client.
However, when I run it from the Azure site, I get the following error:
System.IO.DirectoryNotFoundException: Could not find a part of the
path 'D:\home\site\wwwroot\temp\somefile.csv'.
Does the free version of Azure Websites block us from saving files to disk? If not, where are we allowed to create/save files that we generate on the fly?
Code Example
private FilePathResult SaveVolunteersToCsvFile(List<Volunteer> volunteers)
{
string virtualPathToDirectory = "~/temp";
string physicalPathToDirectory = Server.MapPath(virtualPathToDirectory);
string fileName = "Volunteers.csv";
string pathToFile = Path.Combine(physicalPathToDirectory, fileName);
StringBuilder sb = new StringBuilder();
// Column Headers
sb.AppendLine("First Name,Last Name,Phone,Email,Approved,Has Background Check");
// CSV Rows
foreach (var volunteer in volunteers)
{
sb.AppendLine(string.Format("{0},{1},{2},{3},{4},{5},{6}",
volunteer.FirstName, volunteer.LastName, volunteer.MobilePhone.FormatPhoneNumber(), volunteer.EmailAddress, volunteer.IsApproved, volunteer.HasBackgroundCheckOnFile));
}
using (StreamWriter outfile = new StreamWriter(pathToFile))
{
outfile.Write(sb.ToString());
}
return File(Server.MapPath(virtualPathToDirectory + "/" + fileName), "text/csv", fileName);
}
Make sure that the ~/temp folder gets published to the server, as it's possible your publish process isn't including it.
Azure Websites provide environment variables that you can use to get to things like a temporary storage folder. For example, there is a "TEMP" variable you could access to get a path to the TEMP folder specific to your Website.
Change line 2 in your method to this:
//string physicalPathToDirectory = Server.MapPath(virtualPathToDirectory);
string physicalPathToDirectory = Environment.GetEnvironmentVariable("TEMP");
Then change the last line to this:
//return File(Server.MapPath(virtualPathToDirectory + "/" + fileName), "text/csv", fileName);
return File(pathToFile, "text/csv", fileName);

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,

.NET WCF service can not access local file

After looking at many topics I decided to ask this
I have a WCF service that reads a file from the local file system. When the service is tested locally on my computer it was no problem doing that.
But when I publish the service in IIS8 i am getting this error
The system cannot find the file specified
I have tried creating a new user and new ApplicationPool that uses that identity to run the service and also given full control to the folder that is trying to be read but the problem continues.
I have also tried even using the Administrator as the identity of the new Application Pool but did not solve the problem either
What am i missing ?
Assuming that you have a relative URL and the account that is running the application has the proper permissions, you're probably not getting the correct pathname to your file.
You can try something like this to find the full path of your file:
using System.IO;
public FileInfo GetFileInfo(string filename)
{
if(filename == null)
throw new ArgumentNullException("filename");
FileInfo info = new FileInfo(filename);
if(!Path.IsPathRooted(filename) && !info.Exists)
{
string[] paths = {
Environment.CurrentDirectory,
AppDomain.CurrentDomain.BaseDirectory,
HostingEnvironment.ApplicationPhysicalPath,
};
foreach(var path in paths)
{
if(path != null)
{
string file = null;
file = Path.Combine(path, filename);
if(File.Exists(file))
{
return new FileInfo(file);
}
}
}
}
throw new FileNotFoundException("Couldn not find the requested file", filename);
}
It's returning an instance of System.IO.FileInfo but you can easily adapt it to return a string (full pathname).

Categories

Resources