小编Cav*_*rna的帖子

System.IO.Directory.Exists 在 LINQ 语句内失败,但在 foreach 循环中失败

.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;
}
Run Code Online (Sandbox Code Playgroud)

如果我运行此代码,我会收到此错误:

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.  

Run Code Online (Sandbox Code Playgroud)

更疯狂的是,如果我重写代码,手动调用Directory.Exists并且它可以工作!

private static IEnumerable<string> GetInventorTemplates_WORKS()
{
    var publicPath = Environment.GetEnvironmentVariable("PUBLIC");
    var …
Run Code Online (Sandbox Code Playgroud)

.net c#

2
推荐指数
1
解决办法
107
查看次数

标签 统计

.net ×1

c# ×1