以下几段代码已经运行好几周,但今天我得到了这个例外:
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)
...
Run Code Online (Sandbox Code Playgroud)
这是代码
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
};
}
Run Code Online (Sandbox Code Playgroud)
我想,好吧,deviceId位必须是垃圾,但查看我得到的日志输出:
Definition for '3912'
Run Code Online (Sandbox Code Playgroud)
我认为抛出该异常的代码行如下,但我没有PDB所以我不是100%肯定因此发布整个函数.
var files = info.GetFiles(deviceId + "_????.txt");
Run Code Online (Sandbox Code Playgroud)
我检查了Path.GetInvalidPathChars MSDN页面以查看哪些无效字符,我认为传入"3912_????.txt"该函数应该没问题.
我认为目录必须正常或整个.Exists事情都会崩溃.
所以,任何伟大的StackOverfloweions都知道可能会发生什么事情(我刚刚重新启动我的应用程序并且还没有看到它再次发生......)?
更新
在该目录中执行dir我有以下内容:
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
Run Code Online (Sandbox Code Playgroud)
最可能的原因是deviceId包含无效字符。
例如,尾随空字符(“\0”)将给出此结果,并且可能不会显示在您的日志中。
您可以通过跟踪 deviceId 字符串中每个字符的值来检查这一点 - 例如:
Console.WriteLine("Device Id {0} ({1})",
deviceId,
String.Join("-", deviceId.Select(x => ((int)x).ToString("X2")).ToArray()));
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3430 次 |
| 最近记录: |