我是否必须编写自己的方法来取消文件夹及其内容的 readony 设置?

发布于 2024-08-04 01:30:54 字数 918 浏览 1 评论 0原文

我有一个文件夹,其中包含一些文件夹,这些文件夹中包含一些文件。碰巧这些文件可能是只读的,这对我来说是不可接受的。

问题是我是否必须编写代码以递归地取消所有文件的只读设置?写起来并不难,但是有没有标准的.NET 方法可以做到这一点?

我当前的解决方案:

private static void SetReadOnly( string path, bool readOnly )
{
    foreach ( string directory in Directory.GetDirectories( path ) )
    {
        DirectoryInfo di = new DirectoryInfo( directory );
        if ( readOnly )
        {
            di.Attributes &= FileAttributes.ReadOnly;
        }
        else
        {
            di.Attributes ^= FileAttributes.ReadOnly;
        }

        SetReadOnly( directory, readOnly );
    }

    foreach ( string file in Directory.GetFiles( path ) )
    {
        FileInfo fi = new FileInfo( file );
        if ( readOnly )
        {
            fi.Attributes &= FileAttributes.ReadOnly;
        }
        else
        {
            fi.Attributes ^= FileAttributes.ReadOnly;
        }
    }
}

I have a folder with some folders in it and some files in those folders. It so happens, that those file may be readonly which is not acceptable for me.

The questions is do I have to write the code to recursively unset readonly on all files? It's not difficult to write but is there any standard .NET way to do it?

My current solution:

private static void SetReadOnly( string path, bool readOnly )
{
    foreach ( string directory in Directory.GetDirectories( path ) )
    {
        DirectoryInfo di = new DirectoryInfo( directory );
        if ( readOnly )
        {
            di.Attributes &= FileAttributes.ReadOnly;
        }
        else
        {
            di.Attributes ^= FileAttributes.ReadOnly;
        }

        SetReadOnly( directory, readOnly );
    }

    foreach ( string file in Directory.GetFiles( path ) )
    {
        FileInfo fi = new FileInfo( file );
        if ( readOnly )
        {
            fi.Attributes &= FileAttributes.ReadOnly;
        }
        else
        {
            fi.Attributes ^= FileAttributes.ReadOnly;
        }
    }
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

別甾虛僞 2024-08-11 01:30:54

不,没有内置方法可以实现这一点。您必须自己编写它,并且您现有的代码看起来可以完成这项工作。

No, there's no built-in method for that. You have to write it yourself, and your existing code looks like it would do the job.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文