public string GetLogPath(string customDirectory, string preFile) { string newFilePath = string.Empty; //String logDir = string.IsNullOrEmpty(customDirectory) ? Path.Combine(Environment.CurrentDirectory, "logs") : customDirectory; String logDir = string.IsNullOrEmpty(customDirectory) ? PathHelper.CombineWithBaseDirectory("logs") : customDirectory; if (!Directory.Exists(logDir)) { Directory.CreateDirectory(logDir); } string extension = ".log"; string fileNameNotExt = String.Concat(preFile, DateTime.Now.ToString("yyyyMMdd")); String fileName = String.Concat(fileNameNotExt, extension); string fileNamePattern = string.Concat(fileNameNotExt, "(*)", extension); List <string> filePaths = new List <string>(Directory.GetFiles(logDir, fileNamePattern, SearchOption.TopDirectoryOnly)); List <string> correctFilePaths = new List <string>(); if (filePaths.Count > 0) { foreach (string fPath in filePaths) { string no = new Regex(@"(?is)(?<=\()(.*)(?=\))").Match(Path.GetFileName(fPath)).Value; int tempno = 0; if (int.TryParse(no, out tempno)) { correctFilePaths.Add(fPath); } } } if (correctFilePaths.Count > 0) { correctFilePaths.Sort((x, y) => x.CompareTo(y)); int fileMaxLen = 0; for (int i = 0; i < correctFilePaths.Count; i++) { int itemLength = correctFilePaths[i].Length; fileMaxLen = itemLength > fileMaxLen ? itemLength : fileMaxLen; } string lastFilePath = correctFilePaths.FindLast(d => d.Length == fileMaxLen); long actualSize = new FileInfo(lastFilePath).Length; long maxSize = 10 * 1024 * 1024;//(1 * 1024 * 1024 = 1M); if (actualSize < maxSize) { newFilePath = lastFilePath; } else { string no = new Regex(@"(?is)(?<=\()(.*)(?=\))").Match(Path.GetFileName(lastFilePath)).Value; int tempno = 0; bool parse = int.TryParse(no, out tempno); string formatno = String.Format("({0})", parse ? (tempno + 1) : tempno); string newFileName = String.Concat(fileNameNotExt, formatno, extension); newFilePath = Path.Combine(logDir, newFileName); } } else { string newFileName = String.Concat(fileNameNotExt, String.Format("({0})", 0), extension); newFilePath = Path.Combine(logDir, newFileName); } return(newFilePath); }