The following code snippet works fine for several weeks, but today I got this exception:
System.ArgumentException: Illegal characters in path. at System.IO.Path.CheckInvalidPathChars(String path) at System.IO.Path.InternalCombine(String path1, String path2) at System.IO.FileSystemEnumerableIterator`1.GetFullSearchString(String fullPath, String searchPattern) at System.IO.FileSystemEnumerableIterator`1..ctor(String path, String originalUserPath, String searchPattern, SearchOption searchOption, SearchResultHandler`1 resultHandler) at System.IO.DirectoryInfo.InternalGetFiles(String searchPattern, SearchOption searchOption) at System.IO.DirectoryInfo.GetFiles(String searchPattern) at MyCompany.GetSendDefinition(String deviceId) ...
Here is the code
public SendDefinition GetSendDefinition(string deviceId) { Logger.Debug("Definition for '{0}'" deviceId); string storePath = Path.Combine(_serviceFolder, TcpFolder); var info = new DirectoryInfo(storePath); if (!info.Exists) { return null; } var files = info.GetFiles(deviceId + "_????.txt"); int numberOfMessage = files.Length; var file = files.OrderBy(x => x.CreationTime).FirstOrDefault(); if (file == null) { return new SendDefinition { Message = string.Empty, NumberOfMessages = 0 }; } string response; using (var reader = new StreamReader(file.FullName)) { response = reader.ReadToEnd().Replace("\r\n", ""); } string[] data = file.Name.Split('.'); var name = data[0].Split('_'); if (name.Length > 3) { var count = Convert.ToInt16(name[3], CultureInfo.InvariantCulture); if (count < 5) { count++; string newFileName = Path .Combine(storePath, data[0].Substring(0, data[0].Length - 1) + count + ".txt"); file.CopyTo(newFileName, true); } file.Delete(); } else { string newFileName = Path.Combine(storePath, data[0] + "_0.txt"); file.CopyTo(newFileName, true); file.Delete(); } return new SendDefinition { Message = response, NumberOfMessages = numberOfMessage }; }
I thought, OK, the deviceId bit should be garbage, but looking at the output log, I got:
Definition for '3912'
I think the line of code that will throw this exception is the following, but I don't have a PDB, so I'm not 100% sure, so I'm sending the whole function.
var files = info.GetFiles(deviceId + "_????.txt");
I checked the Path.GetInvalidPathChars MSDN page to find out which characters are invalid and I think that passing "3912_????.txt" to this function should be fine.
I believe the directory should be fine, or the whole .Exists thing .Exists fall.
So any of the great StackOverfloweions knows what this could do (I just restarted the application and haven't seen it again ...)?
Update
Running a directory in this directory I have:
14.03.2012 16:03 <DIR> . 14.03.2012 16:03 <DIR> .. 09.03.2012 13:51 101 3055_P_275112090312.txt 25.01.2012 10:52 99 3055_X_325209250112.txt 10.02.2012 08:38 74 3055_Z_373807100212.txt 3 Datei(en) 274 Bytes 2 Verzeichnis(se), 33.613.897.728 Bytes frei