I have a piece of code that saves my processed file at a location. If there is data at that file that is any subdirectory or files then the directory is first deleted and then processed file is stored there. Now if i give the path as C:\ then all the data in C:\ drive will get deleted. I dont want this. I want to put a check if the location given is the any of the partition that is C:\ or D:\ then it should not get deleted. Can anybody tell me the syntax?
views:
148answers:
6If the first char is a letter and the second char is a colon and the length of the string is 2 or 3, disallow it.
EDIT: Or just check for the colon and the length. One less check.
string partition = "C:\\";
DirectoryInfo di = new DirectoryInfo(partition);
if (di.Root.ToString() == partition)
{
// this is the root directory
}
If you have a variable file
that holds your file name you could do something like this:
using System.Linq;
string file = "c:\filename.txt";
FileInfo fileInfo = new FileInfo(file);
if (Directory.GetLogicalDrives().Contains(fileInfo.DirectoryName))
{
// File is in root of drive
}
else
{
// File is in a sub-folder
}
(This was tested for "Intellisense-quality", i.e. it should compile, but it might not run 100% correctly, so please test before you decide to use it.)
You can enumerate all logical drives and just check if the provided savepath corresponds with one of the root drivepaths
bool okToDelete = true; string savePath = GetSaveLocation(); string[] fixedDrives = Environment.GetLogicalDrives(); // Loop into the string array foreach (string drive in fixedDrives) { if (savePath.Equals(drive, StringComparison.OrdinalIgnoreCase)) { okToDelete = false; break; } } if (okToDelete) { //continue deleting data }
You should not do it that way. You should use code access security to restrict your application to have access only to the directories that it should be operating on. Check out the FileIOPermissionAttribute. Here's an example of restricting an application's file rights (it's an ASP.NET example, but concept is similar).
You should also run your application under a user account that does not have high rights NTFS access to file locations that it should not be deleting from.
If you're actually worried about the class of disk drive you are writing to (e.g. only write to removable media) then here is an answer to that http://stackoverflow.com/questions/1124463/how-to-get-the-list-of-removable-disk-in-c