Save file to App_Data folder error - asp.net

I am trying to save a pdf file generated using Rotativa to the app_data folder of my web app but I get the error :
System.IO.DirectoryNotFoundException: Could not find a part of the path 'E:\www\tsp13amp\website.com\wwwroot\App_Data\Documents\Corps_Profile_userID.pdf'.
My Controller code :
var PDF = new Rotativa.ViewAsPdf("ProfilePrint", model) { FileName = "Corps_Profile_" + User.Identity.GetUserId() + "_" + DateTime.Now.ToString("dd-MM-yyyy")};
var fileName = PDF.FileName;
byte[] pdfBytearray = PDF.BuildPdf(ControllerContext);
var fullPath = Path.Combine(Server.MapPath("~/App_Data/Documents/"),fileName +".pdf");
var byteArray = PDF.BuildPdf(ControllerContext);
System.IO.File.WriteAllBytes(fullPath, byteArray)
What I am trying to do is to store the file in the App_Data folder and a reference to the file in the database which will then be used a link to the file later on like:
Download
Thanks for any help.

Just to make this official - don't store anything in your app_data unless you specifically have a way it will be used. This folder is not mapped by default to return content, as such you'd need an HttpHandler or something specific to serve files from this folder. If you map them to a name in the database you'd still need a way to return them.
You are much better served creating another folder to use for this.

Related

Extracting Windows File Properties with http link

I am working on this problem and the proposed solution works for me.
However, now I need to make this work in my actual application which is an AWS Beanstalk .NET web application. My beanstalk application knows the url source of the picture. Knowing the url, I can get a stream and process the file (by creating a byte array and even a Bitmap object).
However, it seems that to get the file properties as mentioned above (such as the camera type or painting application that created the file), I really need a local file because that is the expected input argument.
This is a problem for me. I know the http link, I know the bytes but I have no such thing as a file path.
How can I solve this? I need the windows file properties.
If I understood you correctly, you want to read image metadata from a URL without saving it to a file first, i.e. directly from the Internet.
Here is one way that works for me:
string demoImageUrl = "https://raw.githubusercontent.com/ianare/exif-samples/master/jpg/Canon_40D.jpg";
byte[] imgData = null;
using (var wc = new WebClient())
{
imgData = wc.DownloadData(demoImageUrl);
}
using (var sr = new MemoryStream(imgData, false))
{
BitmapSource image = BitmapFrame.Create(sr);
BitmapMetadata md = (BitmapMetadata)image.Metadata;
string comment = md.Comment;
string title = md.Title;
string dateTaken = md.DateTaken;
}
You need to add references to PresentationCore and WindowsBase assemblies and also include the following namespace:
using System.Windows.Media.Imaging;

Upload File with FileUpload and Stock in database using Framwork entity

I want to upload file with file upload and stock in DataBase SQLserver using framework entity , I use this code :
string strRealPath = Request.PhysicalApplicationPath;
if(FileUpload1.HasFile)
{
string fileName = FileUpload1.FileName;
FileUpload1.SaveAs(strRealPath + fileName);
//Now insert the file into the database.
}
f.photo = Convert.ToString(FileUpload1.FileBytes);
But I find anything added .I use the debugger he tell me that posted file is null
Thanks
Firstly, your form should be encrypted as multipart/form-data. Add parameter to your form tag like below:
enctype = "multipart/form-data"
Secondly you have to send file as controller parameter HttpPostedFile.
This tutorial will be useful for you. Let us know, does it work properly.
===EDIT===
When it comes to database. You have to have column of binary type (varbinary[max]), and you
should try save it there (remember about try/catch). To read content of the file, use stream reader.

how to get the list of the images from the Application Directory

I am Developing a Web site and i need to read all the images from the images folder in the
application directory and i have to display all the images on the page can any body tell me how to read all the images from the images folder which is in my application directory.
Thanks in Advance.
This could help
https://web.archive.org/web/20210304125318/https://www.4guysfromrolla.com/articles/052803-1.aspx
To add to the answer of Mr. Disappointment, you can get a list of all the files using the command specified,
To get the path of the application using Server.MapPath.
Then getting the list of files, you can simply iterate and filter on the extensions you need.
This will get you an array of the file names in a given path:
string[] fileNames = System.IO.Directory.GetFiles(yourPath);
You can then generate URLs for them and use <img> tags written out to the response, for example something like ought to get the valid URLs:
string relativePath = Request.AppRelativeCurrentExecutionFilePath;
relativePath = relativePath.Substring(0, relativePath.LastIndexOf('/') + 1);
string requestPath = Path.GetDirectoryName(Server.MapPath(relativePath));
string[] fileNames = Directory.GetFiles(requestPath);
List<string> imageUrls = new List<string>(fileNames.Length);
foreach(var fileName in fileNames)
{
imageUrls.Add(Path.Combine(relativePath, Path.GetFileName(fileName)));
}
You could just write out the <img> items in the loop. Also, note that a call to GetFiles supplying only a path will return all available files so you might want to supply a searchPattern argument such as *.jpg.

storing the files in a web application in asp.net

I have set of components that i wish to let the users download from my web application.
Now the question is where should i place the files in app_data or create a separate folder in asp.net web application as shown here or is there any other optimal solution for this ?
What i mean by components is you can take a look at this ! So what is the best way to do store the components ?
Right now what i'm doing is: i'm storing the files in a external folder outside the application more specifically in documents folder of my c drive, and i'm storing the path to a component as a data element of the table, when ever user clicks on a particular row's button (in the grid view) i'm getting the title of that particular clicked row and querying the database table for the filepath of that component title using these lines of code:
String filePath = dr1[0].ToString(); //GETS THE FILEPATH FROM DATABASE
HttpContext.Current.Response.ContentType = "APPLICATION/OCTET-STREAM";
String disHeader = "Attachment; Filename=\"" + filePath + "\"";
HttpContext.Current.Response.AppendHeader("Content-Disposition", disHeader);
System.IO.FileInfo fileToDownload = new System.IO.FileInfo(filePath);
HttpContext.Current.Response.Flush();
HttpContext.Current.Response.WriteFile(fileToDownload.FullName);
Am i doing it properly ? Is there a better/optimal way to do it ?
A user simply needs read access to download a file, so you can simply create a directory claled "Downloads" and place them in there.
You can ensure that people can't "browse" that directory by disabling Directory Browsing and not placing any default docs in there (index.html, default.aspx for example)
What you are currently doing looks like a fairly standard way for providing downloads off your site.
I can't think of something more "optimal".

Httphandler Version Aspx Code Behind writing Image file

We have encountered this difference in file creation while using a HttpHandler Versus a Code Behind Aspx page.
We are reading a saved jpg/png picture as byte array from a 'Image' field in sql server database and create a physical file in the server.
Both the Aspx Page and Httphandler use the same code pasted below.
//Begin
int docID = Convert.ToInt32(Request.QueryString["DocID"]);
var docRow = documentDB.GetDocument(docID);
// Retrieve the physical directory path for the Uploads subdirectory
string destDir = Server.MapPath("../../Uploads").ToString() + "\\";
string strFileName = destDir + DateTime.Now.ToFileTime() + "_" + docRow.DocName.ToString();
FileStream fs = new FileStream(strFileName, FileMode.CreateNew, FileAccess.Write);
fs.Write(docRow.DocData, 0, docRow.DocData.Length);
fs.Flush();
fs.Close();
// End
After the file is created, it is viewable as a jpg/png Image only in Aspx Code Behind. While in case of HttpHandler it is not a valid Image.
Any ideas for this behavior/missing link/resolution steps will be helpful.
Thank you.
Finally isolating different steps the problem was identified to be the data being stored into Database Table.
The way to eliminate this issue was during upload of file, Create a physical file on the server local system. Read this file into a byte array and store into the Database Table. (Could be Encoding Issue)

Resources