.Net 框架 4.7.2
這是一個非常令人驚訝的問題......
我有這個例程可以從本地磁盤獲取所有可用的 Inventor 模板,無論它是哪個版本:
private static IEnumerable<string> GetInventorTemplates_FAILS()
{
var publicPath = Environment.GetEnvironmentVariable("PUBLIC");
var autodeskPath = Path.Combine(publicPath, "Documents", "Autodesk");
var inventorPaths = Directory.GetDirectories(autodeskPath, "*Inventor*");
var templatePaths = inventorPaths.Select(path => Path.Combine(path, "Templates"));
var templates = templatePaths.Where(Directory.Exists).SelectMany(path => Directory.GetFiles(path, "*.*", SearchOption.AllDirectories));
// throws error ^^^^^^^^^^^^^^^^
return templates;
}
如果我運行此代碼,則會收到此錯誤:
System.Linq.SystemCore_EnumerableDebugView`1[System.String].get_Items() calls into native method Microsoft.Win32.Win32Native.GetFullPathName(char*, int, char*, System.IntPtr). Evaluation of native methods in this context is not supported.
更瘋狂的是,如果我重寫代碼,手動呼叫Directory.Exists它就可以了!!!
private static IEnumerable<string> GetInventorTemplates_WORKS()
{
var publicPath = Environment.GetEnvironmentVariable("PUBLIC");
var autodeskPath = Path.Combine(publicPath, "Documents", "Autodesk");
var inventorPaths = Directory.GetDirectories(autodeskPath, "*Inventor*");
var templatePaths = inventorPaths.Select(path => Path.Combine(path, "Templates"));
foreach (var path in templatePaths)
if (Directory.Exists(path)) // <- no exception!!!
foreach (var template in Directory.GetFiles(path, "*.*", SearchOption.AllDirectories))
yield return template;
}
如果您只是通過QuickWatch檢查,您將得到相同的結果:


現在我可以使用重寫的版本,但我很好奇我是否是幸運的...... :-)
uj5u.com熱心網友回復:
這不是 .NET 問題。代碼將運行良好,您無需更改任何內容。除錯器說它不能在監視視窗中安全地執行查詢,所以它不能顯示任何結果。該錯誤解釋說
不支持在此背景關系中評估本機方法。
template不是檔案串列,而是尚未執行的查詢。除錯器必須執行該查詢來檢索結果。
這既不是問題也不是不常見的。在某些情況下,除錯器無法安全地執行 LINQ 查詢或列舉 IEnumerable 并顯示結果。如果要檢查結果,請顯式執行查詢,例如使用ToList.
附言
使用像Glob(3M NuGet 下載)這樣的 globbing 庫來替換所有這些代碼可能是個好主意:
var root = new DirectoryInfo(autodeskPath);
var templates = root.GlobFileSystemInfos("*Inventor*/Templates/**/*.*");
.NET Core 本身通過Microsoft.Extensions.FileSystemGlobbing包使用檔案通配符。
Matcher matcher = new();
matcher.AddIncludePatterns(new[] { "*Inventor*/Templates/**/*.*" });
foreach (string file in matcher.GetResultsInFullPath(autodeskPath))
{
Console.WriteLine(file);
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/457500.html
