File Checking in C#
I'm currently writing a logger in C# and want to be able to change the file I'm writing to, like so:
[ConditionalAttribute("DEBUG")]
static void SetPath(string path)
{
if (File.Exists(path) && (File.GetAttributes(path) & FileAttributes.Normal) == FileAttributes.Normal)
fileName = path;
else
throw new InvalidOperationException("File seems important...");
// Other logic here.
}
I realize that a programmer (even me) could accidentally jumble up a path and delete something important.开发者_开发技巧 Is this a valid fear? Even though there are only two programmers on this project, I want to know if there is a way to make sure that more important files are not overwritten. It's fine if they don't exist, they'll just be created then.
My other thought is that the log file should have a specific ending (e.g. ".log") and any file not containing that ending cannot be overwritten. I'm not sure how "protective" my if-statement is. Does this protect against me from overriding important files?
Sounds slightly over-paranoid, IMHO. I'd make sure that the path is not end-user changeable and then just have enough unit tests to find out while developing when stuff breaks (instead of when deploying to customers).
Feel to me that you are crossing the river for water? Instead, why not by practice write your log files to either a subdirectory of the .exe file:
Path.GetDirectoryName(Application.ExecutablePath)
or a system special folder ie:
Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData) + "\\MyProgram\\logs";
But if you really want to go down the path you suggested, then you could also check out the file attributes, "hidden" and "system" fileattributes at msdn
精彩评论