Using the Security System for Defensive Coding
Darren Neimke points out that you can often run into trouble by not checking variables past in by users. You can view his scenario here.
Now, while I support parameter checking, there is also a feature of the .NET Framework that would give him the same functionality as parameter checking in a much safer fasion. The FileIOPermission object can be used to deny access to all but selected paths. So here goes:
private void MyForm_Load( ... ) {
string niceFile = @"..\File.txt";
string path = @"c:\SafeScripts\";
string fullPath = System.IO.Path.Combine(path, niceFile);
label1.Text = ReadFromFile(fullPath, safePath);
}
private string ReadFromFile(string fileName, safePath) {
string retVal = null;
FileIOPermission ioPerm = new FileIOPermission(FileIOPermissionAccess.Read, safePath);
try {
ioPerm.PermitOnly();
using(StreamReader sr = new StreamReader(File.OpenRead(fileName))) {
retVal = sr.ReadToEnd();
sr.Close();
}
} catch {
retVal = "An error occurred accessing file: " + fileName;
} finally {
ioPerm.RevertPermitOnly();
}
return retVal;
}
I love making use of the various permissions whenever possible. It makes me feel like my application is going to be secured not only by me, but months of testing and security reviews Microsoft has done as well. If a new form of hack is found that mangles the path name, I can then rely on the MS security fix process to ensure my application gets access to updated protections as well.