【问题标题】:C# How to change FileAttributes from Normal to DirectoryC# 如何将 FileAttributes 从 Normal 更改为 Directory
【发布时间】:2014-11-25 22:03:46
【问题描述】:

我的一个朋友给了我一张损坏的 SD 卡,其中将“DCIM”文件夹显示为文件。 我编写了一个控制台程序来显示 FileInfo,它返回“正常”。现在我尝试将 FileAttributes 从“正常”更改为“目录”,如示例中所示:http://msdn.microsoft.com/de-de/library/system.io.file.setattributes%28v=vs.110%29.aspx

static void Main(string[] args)
    {
        var path = "O://DCIM";
        FileAttributes attributes = File.GetAttributes(path);
        attributes = RemoveAttribute(attributes, FileAttributes.Normal);
        var attr = attributes | FileAttributes.Directory;
        File.SetAttributes(path, attr);

        var fi = new FileInfo(path);
        Console.WriteLine(fi.Name + " -- " + fi.Attributes);
        Console.ReadKey();
    }

    private static FileAttributes RemoveAttribute(FileAttributes attributes, FileAttributes attributesToRemove)
    {
        return attributes & ~attributesToRemove;
    }

程序按预期运行,当我在分配它之前检查 attr 时,它返回“目录”。但最后,FileAttributes 仍然是“Normal”。

是否可以通过这种方式更改 FileAttributes? 有另一种解决方案吗?

【问题讨论】:

  • 实用部分——“如何从损坏的磁盘中恢复文件”在superuser.com/tour 上可能没问题;关于在磁盘上读取/写入原始数据的讨论对于 SO 来说可能过于广泛,但已经有很多问题了。其余部分由 Jim Mischel 回答为“否”。
  • 我很奇怪File.SetAttributes 没有抛出异常。查看参考源,它显示File.SetAttributes 调用SetFileAttributes,如果SetFileAttributes 返回0,则抛出异常。显然SetFileAttributes 在尝试将文件转换为目录时不会因错误退出。好奇。
  • 是的,如果有错误我不会问。但一切似乎都很好,只是没有。

标签: c# file-attributes


【解决方案1】:

根据SetFileAttributes API 函数的文档,对File.SetAttributes 的调用解析为:

文件不能转换成目录。

如果您想从该设备获取信息,则必须使用低级设备 I/O 读取原始扇区。这是可能的,但工作量很大。

如果您对从该设备获取信息是认真的,不要尝试对其进行写入。数据已损坏。尝试修改该设备上的数据更有可能进一步破坏那里的数据。使用低级阅读器读取硬盘驱动器上文件的二进制图像。然后制作该文件的副本,然后您就可以在副本上打自己了。

当然,您可能想问问自己,该驱动器上的数据是否真的值得您为尝试恢复它而付出努力。数据恢复可能非常乏味。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-07-26
    • 2021-09-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多