【问题标题】:PathTooLongException in new FileInfo新 FileInfo 中的 PathTooLongException
【发布时间】:2017-08-08 07:28:11
【问题描述】:

我有以下代码:

    static long getFolderSize(string path)
    {
        string[] a = Directory.GetFiles(path, "*.*", SearchOption.AllDirectories);

        long b = 0;
        foreach (string name in a)
        {
            FileInfo fi = new FileInfo(name);
            b += fi.Length;
        }

        return b;
    }

在运行此代码的环境中,存在超过 260 个字符限制的路径。因此行

FileInfo fi = new FileInfor(name);

抛出 System.IO.PathTooLongException。

我已经阅读了很多关于此的内容,根据https://blogs.msdn.microsoft.com/jeremykuhne/2016/07/30/net-4-6-2-and-long-paths-on-windows-10/,该问题应该在 .NET 4.6.2 中得到解决。因此,我在 .NET 4.7 中编译了代码,但还是一样。

正如this 线程中提到的,我尝试使用Delimon 的库,但它在行中抛出了 System.OverflowException

string[] a = Directory.GetFiles(path, "*.*", SearchOption.AllDirectories);

有人知道如何解决这个问题吗? (我无法更改文件结构,也无法使用映射驱动器)。

谢谢

编辑:

我加了

<runtime>
    <AppContextSwitchOverrides value="Switch.System.IO.UseLegacyPathHandling=false;Switch.System.IO.BlockLongPaths=false"/>
</runtime>

到 app.config(注意它是一个控制台应用程序)。现在一行中抛出了一个 System.IO.FileNotFoundException

b += fi.Length;

编辑2:

app.config 文件如下所示:

<?xml version="1.0"?>
<configuration>
    <runtime>
        <AppContextSwitchOverrides value="Switch.System.IO.UseLegacyPathHandling=false;Switch.System.IO.BlockLongPaths=false"/>
        <runtime targetFramework="4.7"/>
            <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.7"/>
        </runtime>
        <appSettings>
            <add key="SQLServer" value="Server2"/>
            <add key="database" value="FolderSizeMonitor"/>
            <add key="server" value="Server3"/>
        </appSettings>
        <startup>
            <dir ID="1" path="\\server20\d$\Data\BEG\Emergency\Emergency Management\Very Very Very Long pathVery Very Very Long path" DepthToLook="4">
            </dir>
    </startup>
</configuration>

【问题讨论】:

标签: c# .net file path


【解决方案1】:

下面的代码成功了:

    static long getFolderSize(string path)
    {
        DirectoryInfo dirInfo = new DirectoryInfo(path);

        long b = 0;
        foreach(FileInfo fi in dirInfo.EnumerateFiles("*",SearchOption.AllDirectories))
        {
            b += fi.Length;
        }

        return b;
    }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-09-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多