下面的代码片段几周来都运行良好,但今天我遇到了这个异常:
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)
...
这是代码
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
};
}
我想,好的,deviceId 位一定是垃圾,但查看我得到的日志输出:
Definition for '3912'
我认为会抛出该异常的代码行如下,但我没有 PDB,所以我不能 100% 确定因此发布整个函数。
var files = info.GetFiles(deviceId + "_????.txt");
我检查了 Path.GetInvalidPathChars MSDN 页面查看什么是无效字符,我认为将 "3912_?????.txt"
传递到该函数应该没问题。
我认为该目录一定没问题,否则整个 .Exists
都会折叠。
那么 StackOverfloweions 中的任何一位大神都知道是什么导致了这种情况发生(我刚刚重新启动了我的应用程序并且还没有看到它再次发生......)?
更新
在那个目录中做一个目录,我有以下内容:
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
最佳答案
最可能的原因是 deviceId
包含无效字符。
例如,尾随空字符 ("\0") 会给出此结果,并且可能不会显示在您的日志中。
您可以通过跟踪 deviceId 字符串中每个字符的值来检查这一点 - 例如:
Console.WriteLine("Device Id {0} ({1})",
deviceId,
String.Join("-", deviceId.Select(x => ((int)x).ToString("X2")).ToArray()));
关于c# - 什么会导致 Directory.GetFiles 出现此 ArgumentException?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9704932/