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".
Related
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.
I have an ASP.NET web application that allows the user to upload a file from his PC to a SQL Server database (which is later used to generate an image for an tag). Is there an "easy" way to test the image within .NET to validate that it does not contain anything malicious before saving it?
Right now, I use this:
MemoryStream F = new MemoryStream();
Bitmap TestBitmap = new Bitmap(Filename);
TestBitmap.Save(F, System.Drawing.Imaging.ImageFormat.Png);
int PhotoSize = (int)F.Length;
Photo = new byte[PhotoSize];
F.Seek(0, SeekOrigin.Begin);
int BytesRead = F.Read(Photo, 0, PhotoSize);
F.Close();
Creating TestBitmap fails if it is not an image (e.g. if Filename is the name of a text file), but apparently this doesn't stop a file that is an image with malicious code appended to it from loading as an image, so saving it as a MemoryStream and then writing the stream to a byte array (which is later saved in the database) supposedly fixes this.
To avoid people pass programs and other information's using the ability to upload photos to your site you can do two main steps.
Read and save again the image with your code to remove anything elst.
Limit the size of each image to a logical number.
To avoid some one upload bad code and run it on your server you keep an isolate folder with out permission to run anything. More information's about that on:
I've been hacked. Evil aspx file uploaded called AspxSpy. They're still trying. Help me trap them‼
And a general topic on the same subject: Preparing an ASP.Net website for penetration testing
So I have written a simple program that creates an html document based on user input into a number of fields. Currently, when the user pressed a button it generates the document and automatically downloads onto the user's machine using the following:
Response.ContentType = "text/plain";
Response.Write(HTML.ToString());
Response.Flush();
Response.End();
But, I would like to have the file written to a folder on the user's machine when a user presses a button. So, let's say I want them to press the button and it automatically writes the file to their desktop. What would this code look like? (c#)
Thank you,
p.s. I have been trying something like this with no luck:
string filename = Server.MapPath("~/C:/Users/Sean/Desktop/new.html");
System.IO.StreamWriter textWriter = default(System.IO.StreamWriter);
textWriter = System.IO.File.AppendText(filename);
textWriter.Write(HTML);
textWriter.Close();
Using ASP.Net, you CANNOT force user to save any file on any specific location. Moreover the file you want user to save is HTML which will be rendered directly on browser i.e. user will not be prompted to save it on their machine.
So to answer your question, you cannot have ANY file automatically saved to user's machine. There has to be some manual intervention by the user(to select the path at which he/she wants to save it.)
I am trying to save a jpeg image in an uploads folder which has correct permissions setup. When I test the file is being saved (eg: images/uploads/Winter.jpg) but if I try to view the image in my browser or if I attempt to open the image using anything else the image does not display.
I think that the file is not being encoded correctly before saving it to disk but am not very experienced dealing with the saving of files, encoding. Does the below code look ok or do I need to encode the file being uploaded somehow before saving it to disk?
String imgPath = "newsletter\\images\\uploads\\";
String filename = System.IO.Path.GetFileName(upload.PostedFile.FileName);
filepath = imgPath + filename;
filepath = Request.PhysicalApplicationPath + filepath;
upload.PostedFile.SaveAs(filepath);
The file saves to the correct folder but is only 150bytes in size. If I try to browse to the file and view it with an image viewer it does not display correctly.
Encoding shouldn't be a problem - the raw data isn't changing. However, it's possible the browser isn't sending all the data, or that the upload control is deleting the data before you're saving it.
Make sure that you call .SaveAs() before the page begins unloading, and before any additional postbacks. I think we'll need to see more surrounding code to help further.
Another note - by allowing the existing file extension to be used, you're allowing users to upload .aspx files, which could subsequently be executed through a request. Safe filenames are GUIDs and whitelisted file extensions. Using un-sanitized uploaded path information is very dangerous. If you re-use filenames, sanitize them to alphanumerics.
In my project I want to rename the file before it is updating. For example a file in my system like Mycontact.xls. I want to rename it as sasi.xls (it is an excel file). How can I write the code in ASP.NET?
Actually I am using a fileupload control to get the file in and rename the file and upload the renamed file in a folder which is in Solution Explorer.
You can do it with the File.Move method eg:
string oldFileName = "MyOldFile.txt";
string newFileName = "MyNewFile.txt";
File.Move(oldFileName, newFileName);
C# does not provide a file rename function, unfortunately. Anyhow, the idea is to do this:
File.Copy(oldFileName, NewFileName);
File.Delete(oldFileName);
You can also use - File.Move.
Be aware that when that code executes, the owner of the file will turn into the identity you have set on your Application Pool on which the website is running.
That account might not have enough permissions to 'create new' or 'delete' files.
I would advise you to place all read/writable files in a seperate location so you can control the security settings seperately on that part. This will also split off the 'only readable files/executables' (like the aspx and such) from the 'read/writable' files.