6

Has anyone created a new directory from C# with Encrypting File System switched on?

Additionally any information on doing this from an install would be helpful too.

casperOne
  • 73,706
  • 19
  • 184
  • 253
forest
  • 61
  • 1
  • 2

3 Answers3

7

Creating an encrypted directory would be a two step process - create it using Directory.CreateDirectory and then encrypt it using the Win32 function EncryptFile. Sample code -

using System;
using System.IO;
using System.Runtime.InteropServices;

namespace EncryptDir
{
    public class Sample
    {
        DllImport("advapi32.dll", CharSet = CharSet.Auto, SetLastError = true)]
        static extern bool EncryptFile(string filename);

        public static void Main ()
        {
            Directory.CreateDirectory("MyEncryptedDirectory");
            EncryptFile("MyEncryptedDirectory");
        }
}

References:
EncryptFile Function @ MSDN
Handling encrypted files and directories @ MSDN

Anteru
  • 19,042
  • 12
  • 77
  • 121
DotThoughts
  • 759
  • 5
  • 8
  • That's great! Many thanks for this. It's odd that there doesn't seem to be a way to do it just within the .Net class libraries. – forest Jun 27 '11 at 07:55
  • You are welcome! Its often the case that native .net libraries lag Win32 APIs; I wish it were the other way around now!! – DotThoughts Jul 01 '11 at 15:01
1

The managed methods File.Encrypt() and FileInfo.Encrypt() both simply call the native EncryptFile() that is shown in the other answer.

So, no need to go to all the trouble to declare the p/invoke API. Just use the built-in methods.

Peter Duniho
  • 68,759
  • 7
  • 102
  • 136
1

It seems that calling File.EncryptFile also works on directories. I guess it just forwards to EncryptFile internally.

Anteru
  • 19,042
  • 12
  • 77
  • 121