I needed a way to have a set of directories where I would accept filenames from a user that were on the server in those directories or subdirectories of those directories. For example, if on the server they could access c:\data\users\ or any subdirectories, then all filenames passed to the server would have to be under that directory.
Here is the code to implement this.
Web.Config:
<add key="DataDirectories" value="C:/test;c:/temp/"/>
Code (C#):// returns true if file exists and location is ok. Will set status
private bool TestFileLocation()
{
// sql - no test
if (RadioDataProviderValue == 0)
return true;
// we don't test http
if (XmlFilename.Text.ToLower().StartsWith("http://"))
return true;
string xmlFile = MakeCanonical(Path.GetFullPath(XmlFilename.Text));
if (!File.Exists(xmlFile))
return false;
string[] okPaths = null;
NameValueCollection coll = (NameValueCollection)ConfigurationManager.GetSection("WindwardPortal");
if (coll != null)
{
string allowed = coll["DataDirectories"];
if (allowed != null)
okPaths = allowed.Split(new char[] { Path.PathSeparator });
}
if (okPaths == null)
return false;
// walk them to see if we have a match. We use Path on the entries to make sure the capitalization is correct,
// and convert relative paths to absolute.
foreach (string okPath in okPaths)
{
string pathOn = MakeCanonical(Path.GetFullPath(okPath));
if (!pathOn.EndsWith(new string(new char [] {Path.DirectorySeparatorChar})))
pathOn += Path.DirectorySeparatorChar;
if (xmlFile.StartsWith(pathOn))
return true;
}
// didn't match any
return false;
}
// turn into a canonical representation of the filename
private string MakeCanonical(string filename)
{
// change / to \
filename = filename.Replace(Path.AltDirectorySeparatorChar, Path.DirectorySeparatorChar);
// change c: to C:
if ((filename.Length >= 2) && (filename[1] == Path.VolumeSeparatorChar))
filename = Char.ToUpper(filename[0]) + filename.Substring(1);
return filename;
}
Do you find this useful? If so please check out Windward Reports.
