void SetFile() { lock (_thisLock) { // Check directory FileInfo file = new FileInfo(_filename); _filename = file.FullName; file = new FileInfo(_filename); FileInfo dir = new FileInfo(file.Directory.FullName); if (!dir.IsDirectory() || !dir.CanWrite()) { throw new IOException("Cannot write log directory " + dir); } DateTime now = DateTime.Now; if (_timeZoneInfo != null) { now = TimeZoneInfo.ConvertTime(now, _timeZoneInfo); } // Is this a rollover file? string filename = file.Name; int i = filename.ToLower().IndexOf(YYYY_MM_DD); if (i >= 0) { file = new FileInfo(Path.Combine(dir.FullName, filename.Substring(0, i) + now.ToString(_fileDateFormat) + filename.Substring(i + YYYY_MM_DD.Length))); } if (file.Exists && !file.CanWrite()) { throw new IOException("Cannot write log file " + file); } // Do we need to change the output stream? if (output == null || !file.Equals(_file)) { // Yep _file = file; if (!_append && file.Exists) { file.MoveTo(new FileInfo(file.ToString() + "." + now.ToString(_fileBackupFormat)).FullName); } Stream oldOut = output; output = new FileStream( file.FullName, _append ? (FileMode.Append | FileMode.CreateNew) : (FileMode.Truncate | FileMode.CreateNew), FileAccess.Write); if (oldOut != null) { oldOut.Close(); } //if(log.isDebugEnabled())log.debug("Opened "+_file); } } }
public void TestCanWrite() { FileInfo fi = new FileInfo("test.txt"); Assert.IsTrue(fi.CanWrite()); Assert.IsFalse(new FileInfo("C:\\Windows\\System32\\sethc.exe").CanWrite()); try { new FileInfo("C:\\Windows\\System32?\\sethc.exe").CanWrite(); Assert.Fail(); } catch { } }