Setting Windows file security

后端 未结 2 1682
野性不改
野性不改 2020-12-19 12:42

My problem is the opposite that most people have. I\'m generating files locally in C#, but I want them to be marked as blocked. So when a user opens them in an app

2条回答
  •  失恋的感觉
    2020-12-19 13:33

    You need to write the alternate data stream yourself.

    To do this, open the file with CreateFile and write the text using FileStream. Here is a simple exemple that works (tried on my computer).

    [DllImport("kernel32", CharSet = CharSet.Unicode, SetLastError = true)] 
    private static extern SafeFileHandle CreateFile(
    string name, FileAccess access, FileShare share,
    IntPtr security,
    FileMode mode, FileAttributes flags,
    IntPtr template);
    
        public static void Main()
        {
            // Opens the ":Zone.Identifier" alternate data stream that blocks the file
            using (SafeFileHandle handle = CreateFile(@"\\?\C:\Temp\a.txt:Zone.Identifier", FileAccess.ReadWrite, FileShare.None, IntPtr.Zero, FileMode.OpenOrCreate, FileAttributes.Normal, IntPtr.Zero))
            {
                // Here add test of CreateFile return code
                // Then :
    
                using (StreamWriter writer = new StreamWriter(new FileStream(handle, FileAccess.ReadWrite), Encoding.ASCII))
                {
                    writer.WriteLine("[ZoneTransfer]");
                    writer.WriteLine("ZoneId=3");
                }
            }
    

提交回复
热议问题