ASP.NET localized files - asp.net

I've got a web page with a link, and the link is suppose to correspond to a PDF is the given user's language. I'm wondering where I should put these PDF files though. If I put them in App_LocalResources, I can't specify a link to /App_LocalResources/TOS_en-US.pdf can I?

The PDF should definitely not be in the App_LocalResources folder. That folder is only for RESX files.
The PDF files can go anywhere else in your app. For example, a great place to put them would be in a ~/PDF folder. Then your links will have to be dynamically generated (similar to what Greg has shown):
string cultureSpecificFileName = String.Format("TOS_{0}.pdf", CultureInfo.CurrentCulture.Name);
However, there are some other things to consider:
You need a way to ensure that you actually have a PDF for the given language. If someone shows up at your site and has their culture specified as Klingon, it's unlikely that you have such a PDF.
You need to decide exactly what the file format will be. In the example given, the file would have to be named TOS_en-US.pdf. It you want to use the 2-letter ISO culture names, use CurrentCulture.TwoLetterISOLanguageName and then the file name would be TOS_en.pdf.

I would store the filename somewhere with an argument in it (i.e. "TOS_{0}.pdf" ) and then just add the appropriate suffix in code:
string cultureSpecificFileName = string.Format("TOS_{0}.pdf", CultureInfo.CurrentCulture);

Does the PDF have to have the same file name for each of the different languages? If not, put them all into a directory and just store the path in your resources file.

Related

ASP.NET Read Resources values

I have two .resx files: en.resx and he.resx, in the folder App_LocalResources.
I already have two buttons in my web page, clicking each one is supposed to "switch" to the other language's resource file.
I want to simply get a string value located in one of the .resx files.
I tried some of the examples I have found on google, and I asked myself, why do I need to provide an Assembly type and a namespace, when i just want to ask for a string value in my own project?
Why isn't there something like: string val = Resources["en.resx"]["SomeProperty"].Value?
Maybe my whole approach is wrong, and I would like to read your opinions.
Thanks, Guy
using System.Resources;
ResXResourceSet Resource = new ResXResourceSet(HttpContext.Current.Server.MapPath(#"~/Properties/Resource.resx")
String value=Resource.GetStrin("key");

Get file upload data from post data in ASP.NET

I am looping through the posted values on a form with a view to doing something with them (so don't have access to the controls themselves). This is the process I have to take on this project so that is why I'm doing it this way.
On the form I will have a file upload box but I am not sure how I would upload the file that has been selected from it as I can't just do Control.SaveAs(). When I return the posted value using Request.Form.Item[i] I get the file name I chose but not the full path like I would expect.
Can someone point me in the right direction please?
Thanks.
If you want to manipulate the uploaded files directly, and not through a FileUploader control, you should use the Request.Files collection and not the Request.Form
File Upload controls only pass the file name and the contents. I'm not sure why you would need a folder name, especially since the folder name would be for the client - I can't expect that this would have any value to you since you want to save the file on the server.
As I am unsure of your goals, I would recommend using Server.MapPath("~/Folder") to find a suitable folder to save your uploaded files to

Getting extension of the file in FileUpload Control

At the moment i get file extension of the file like :
string fileExt = System.IO.Path.GetExtension(filUpload.FileName);
But if the user change the file extension of the file ( for example user could rename "test.txt" to "test.jpg" ), I can't get the real extension . What's the solution ?
You seem to be asking if you can identify file-type from its content.
Most solutions will indeed attempt the file extension, but there are too many different possible file types to be reliably identifiable.
Most approaches use the first several bytes of the file to determine what they are.
Here is one list, here another.
If you are only worried about text vs binary, see this SO question and answers.
See this SO answer for checking if a file is a JPG - this approach can be extended to use other file headers as in the first two links in this answer.
Whatever the user renames the file extension to, that is the real file extension.
You should never depend on the file extension to tell you what's in the file, since it can be renamed.
See "how can we check file types before uploading them in asp.net?"
There's no way to get the 'real' file extension - the file extension that you get from the filename is the real one. If file content is your concern, you can retrieve the content type using the .ContentType property and verify that it is a content type that you are expecting - eg. image/jpg.

How can I rename a file in ASP.NET?

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.

File uploading: what should be the name of the file to save to?

I am going to add file upload control to my ASP.NET 2.0 web page so that users can upload files. Files will be stored in the server in the folder with the name as of the user. I want to know what is the best option to name the files when saving to server. Needs to consider security, performance, flexibility to handle files etc.
Options I am considering now :
Upload with the same name as of the input file name
Add User Id+Random Number +File name as of the input file name
Create random numbers +Current Time in seconds and save files with that number. Will have one table to map this number with users upload
Anything else? What is the best way?
NEVER EVER use user input for filenames. Don't use the username. User the user id instead (I assume your users have an unique id).
NEVER use the original filename. Use your solution number 3, plus the user id instead of the username.
For your information, PHP had a vulnerability a few years ago: one could forge a HTTP POST request with a file upload, and with a file name like "../../anything.php", and the php _FILES array, supposed to contain sanitized values, didn't detect these kind of file names, so one could write files anywhere in the filesystem.
I'd use a combination of
User ID
A random generated string (e.g. a GUID)
Example PDF file name: 23212-dd503cf8-a548-4584-a0a3-39dc8be618df.pdf
This way, the user can upload as many files as he/she wants, without file name conflict, and you are also able to point out which files belong to which users, just by looking at the file names.
I don't see the need to include any other information in the file name, since upload time/date and such can be retrieved from the file's attributes.
Also, you should store the files in a safe location, which external users, such as visitors of your website, cannot access. Instead, you deliver the file to them through a proxy web page (you read the file from the safe location, and pass the data on to the user). For this solution, a database is needed to keep track of files, their location, etc.
This also makes you able to control which users have access to which files through your code.
Update: Here's a description of how the solution with the proxy web page could be implemented.
Create a Web Form with the name GetFile.aspx
GetFile.aspx takes one query parameter named fileid, which is used to identify the file to get. E.g.: http://www.mypage.com/GetFile.aspx?fileid=100
Use the fileid parameter to lookup the file location in the database, so that it can be read and sent to the user. In the Web Form you use Request.QueryString("fileid") to get the file ID and use it in a query that will look something like this (SQL): SELECT FileLocation FROM UserFiles WHERE FileID = 100
Read the file using a System.IO.FileStream and output its contents through Response.Write. Remember to set the appropriate content type using Response.ContentType first, so that the client browser handles the requested file correctly (see this post on asp.forums.net and the MDSN article which is also referred to in the post, which both discuss a method of determining the appropriate content type automatically).
If you choose this approach, it's easy to implement your own simple security or custom actions later on, such as making sure a user is logged into your web site before you send the file, or that users can only access files they uploaded themselves, or logging which users download which files, etc. The possibilities are endless ;-)
Take a look at the System.IO.Path class as it has lots of useful functions you can utilise, such as:
Check which characters are invalid in a file name:
System.IO.Path.GetInvalidPathChars();
Get a random file name:
System.IO.Path.GetRandomFileName();
Get a unique, randome filename in the temporary directory
System.IO.Path.GetTempFileName();
I would go with option #3. A table mapping these files with users will provide other uses down the road, it always does. If you use the mapping, the only advantage of appending the user name or id to the file is if you are trying to debug a problem.
I'd probably use a GUID instead of a random number but either would work. The important things in my opinion are
No username as part of the filename as any part of the stored file
Never use the original file name as any part of the stored file
Use a random number or GUID to ensure no duplicate file
Adding an user id to the file will help with manual debugging issues
There is more to this than meets the eye...which I am thinking that you already knew!
What sort of files are you talking about? If they are anything even remotely big or in such quantity that the group of files could be big I would immediately suggest that you add some flexibility to your approach.
create a table that stores the root paths to various file stores (this could be drives, unc paths, what ever your environment supports). It will initially have one entry in it which will be your first storage location. An nice attribute to maintain with this data is how much room can be stored here.
maintain a table of file related data (id {guid}, create date, foreign key to path data, file size)
write the file to a root that still has room on it (query all file sizes stored in a root location and compare to that roots capacity)
write the file using a GUID for the name (obfuscates the file on the file system)..can be written without the file extension if security requires it (sensitive files)
write the file according to its create date starting from the root/year{number}/month{number}/day{number}/file.extension
With a system of this nature in place - even though you won't/don't need it up front - you can now more easily relocate the files. You can better manage the files. You can better manage collections of files. Etc. I have used this system before and found it to be quite flexible. Dealing with files that are stored to a file system but managed from a database can get a bit out of control once the file store becomes so large and things need to get moved around a bit. Also, at least in the case of windows...storing zillions of files in one directory is usually not a good idea (the reason for breaking things up by their create date).
This complexity is only really needed when you have high volumes and large foot prints.

Resources