Search code examples
c#file-attributes

C# How to change FileAttributes from Normal to Directory


A friend of mine gave me a corrupted SD Card which shows the "DCIM" folder as file. I wrote a Console program to show me FileInfo, and it returns "Normal". Now I tried to change the FileAttributes from "Normal" to "Directory" like in the sample: 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;
    }

The program runs as expected, when I check attr before it is assigned it returns "Directory". But in the end, FileAttributes are still "Normal".

Is it possible to change FileAttributes this way? Is there another solution to do this?


Solution

  • According to the documentation for the SetFileAttributes API function, which is what the call to File.SetAttributes resolves to:

    Files cannot be converted into directories.

    If you want to get information from that device, you'll have to read raw sectors using low level device I/O. It's possible, but a lot of work.

    If you're serious about getting information from that device, do not attempt to write to it. The data is corrupt. Attempting to modify the data on that device is more likely to further corrupt what's there. Use a low-level reader to read a binary image of what's there to a file on your hard drive. Then make a copy of that file and you can knock yourself out on the copy.

    Of course, you might want to ask yourself if the data on that drive is really worth the work you're going to put into trying to recover it. Data recovery can be frustratingly tedious.