正在被另一个进程使用的文件无法访问

时间:2015-07-16 18:33:09

标签: c# wpf logging

我正在创建记录器以将消息记录到文本文件中。函数DeleteOldLogs()负责删除超过14天的任何日志。 当我运行TestMethod1()时,我收到一个错误“进程无法访问该文件,因为它正被另一个进程使用” 有没有办法避免这个错误?

// TestClass

[TestMethod]
public void TestMethod1()
{
    LoggerViewModel lv = new LoggerViewModel();
    lv.DeleteOldLogs();
}

// LoggerViewModel类。

[Export]
    [PartCreationPolicy(System.ComponentModel.Composition.CreationPolicy.Shared)]
    public class LoggerViewModel : ViewModelBase
    {
        public ObservableCollection<LogItem> LogItems { get; set; }
        public ObservableCollection<LogItem> logItemCollection = new ObservableCollection<LogItem>();
        protected static readonly ILog log = LogManager.GetLogger(typeof(LoggerViewModel));
        private string dirPath = @"C:\LogFolder";

        [ImportingConstructor]
        public LoggerViewModel()
        {
            MemoryAppender memoryAppender = new MemoryAppender();

            BasicConfigurator.Configure(memoryAppender);
            Log();
            var events = memoryAppender.GetEvents();
            foreach (LoggingEvent loggingEvent in events)
            {
                LogItem logItem = new LogItem(loggingEvent.TimeStamp, loggingEvent.Level, loggingEvent.RenderedMessage);
                logItemCollection.Add(logItem);
            }
            LogItems = logItemCollection;
        }

        public void Log()
        {
            string stackTrace = Environment.StackTrace;
            string[] array = stackTrace.Split("\r\n".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
            foreach (string item in array)
            {
                log.Debug(item);
            }
        }

        public void DeleteOldLogs()
        {
            List<string> delPaths = new List<string>();
            foreach(var file in Directory.GetFiles(dirPath))
            {
                FileInfo info = new FileInfo(file);
                DateTime fileCreationDate = info.CreationTime;
                DateTime twoWeeksAgo = DateTime.Today.AddDays(-14);
                if (fileCreationDate < twoWeeksAgo)
                {
                    string delPath = dirPath + @"\" + info.Name;
                    delPaths.Add(delPath);
                }
            }
            foreach(string dp in delPaths)
            {
                FileSystem.DeleteFile(dp, UIOption.OnlyErrorDialogs, RecycleOption.SendToRecycleBin);
            }
        }
    }

0 个答案:

没有答案