C#
C#

help

Root Question Message

VeQox
VeQox8/20/2022
UnauthorizedAccessException [Answered]

So im trying to change a folders icon, setting it manually sometimes removes it again 🤷‍♂️ , so i hope this works for the time beeing.
VeQox
VeQox8/20/2022
class Program
    {
        [DllImport("shell32.dll", CharSet = CharSet.Auto, SetLastError = true)]
        private static extern void SHChangeNotify(
            int wEventId, int uFlags, IntPtr dwItem1, IntPtr dwItem2);

        static void Main(string[] args)
        {
            const string iconFolder = "icons";

            string workingDiretory = Directory.GetCurrentDirectory();
            string[] folders = Directory.GetDirectories(workingDiretory);
            string[] icons = Directory.GetFiles(Path.Combine(workingDiretory, iconFolder));

            for (int i = 0; i < folders.Length && folders[i] != "icons"; i++)
            {
                string folderPath = folders[i];
                string iconPath = icons[i];
                string iconName = Path.GetFileName(iconPath);
                string desktopIniPath = Path.Combine(folderPath, "desktop.ini");
                string hiddenPath = Path.Combine(folderPath, ".hidden");

                string[] desktopIniContent = new string[] 
                { 
                    "[.ShellClassInfo]",
                    $"IconResource={iconName},0",
                    "[ViewState]",
                    "Mode=",
                    "Vid=",
                    "FolderType=Generic"                                   
                };

                string[] hiddenConent = new string[]
                {
                    "desktop.ini",
                    iconName
                };

                File.WriteAllLines(Path.Join(folderPath,"desktop.ini"), desktopIniContent, Encoding.UTF8);
                File.Copy(iconPath, Path.Join(folderPath, iconName));
                File.WriteAllLines(Path.Join(folderPath, ".hidden"), hiddenConent, Encoding.UTF8);

              
VeQox
VeQox8/20/2022
        File.SetAttributes(desktopIniPath,
                    File.GetAttributes(desktopIniPath)
                    | FileAttributes.Hidden
                    | FileAttributes.ReadOnly);
                File.SetAttributes(iconPath,
                    File.GetAttributes(iconPath)
                    | FileAttributes.Hidden
                    | FileAttributes.ReadOnly);
                File.SetAttributes(hiddenPath,
                    File.GetAttributes(hiddenPath)
                    | FileAttributes.Hidden
                    | FileAttributes.ReadOnly);
                File.SetAttributes(folderPath,
                    File.GetAttributes(folderPath)
                    | FileAttributes.ReadOnly);

                SHChangeNotify(0x08000000, 0x0000, (IntPtr)null, (IntPtr)null);
            }


        }
    }
VeQox
VeQox8/20/2022
im getting a UnauthorizedAccessException but i dont know why
VeQox
VeQox8/20/2022
Unhandled exception. System.UnauthorizedAccessException: Access to the path '....\desktop.ini' is denied.
   at Microsoft.Win32.SafeHandles.SafeFileHandle.CreateFile(String fullPath, FileMode mode, FileAccess access, FileShare share, FileOptions options)
   at Microsoft.Win32.SafeHandles.SafeFileHandle.Open(String fullPath, FileMode mode, FileAccess access, FileShare share, FileOptions options, Int64 preallocationSize)
   at System.IO.Strategies.OSFileStreamStrategy..ctor(String path, FileMode mode, FileAccess access, FileShare share, FileOptions options, Int64 preallocationSize)
   at System.IO.Strategies.FileStreamHelpers.ChooseStrategyCore(String path, FileMode mode, FileAccess access, FileShare share, FileOptions options, Int64 preallocationSize)
   at System.IO.Strategies.FileStreamHelpers.ChooseStrategy(FileStream fileStream, String path, FileMode mode, FileAccess access, FileShare share, Int32 bufferSize, FileOptions options, Int64 preallocationSize)
   at System.IO.StreamWriter.ValidateArgsAndOpenPath(String path, Boolean append, Encoding encoding, Int32 bufferSize)
   at System.IO.File.WriteAllLines(String path, IEnumerable`1 contents, Encoding encoding)
   at SetFolderIcon.Program.Main(String[] args) in 
Program.cs:line 46
VeQox
VeQox8/20/2022
 File.WriteAllLines(Path.Join(folderPath,"desktop.ini"), desktopIniContent,Encoding.UTF8);
VeQox
VeQox8/20/2022
this throwes the error
VeQox
VeQox8/20/2022
but how does it not have access if the file doesnt even exist?
RazorSharpFang
RazorSharpFang8/20/2022
The application may not have write access to the folder itself
RazorSharpFang
RazorSharpFang8/20/2022
UnauthorizedAccessException
path specified a file that is read-only.

-or-

path specified a file that is hidden.

-or-

This operation is not supported on the current platform.

-or-

path is a directory.

-or-

The caller does not have the required permission.
VeQox
VeQox8/20/2022
well how do i check if my program has write access to the folder :Hmm:
RazorSharpFang
RazorSharpFang8/20/2022
Try out DirectoryInfo of the target directory
Check its Attributes property which is of type FileSystemInfo
VeQox
VeQox8/20/2022
VeQox
VeQox8/20/2022
:Hmm:
VeQox
VeQox8/20/2022
seems like thats the issue
RazorSharpFang
RazorSharpFang8/20/2022
If this solves your issue, close the post by using command /close
VeQox
VeQox8/20/2022
well kinda, im just trying to figure it out how to change that without having to go through every folder
RazorSharpFang
RazorSharpFang8/20/2022
Change its attributes so you can write to it?
VeQox
VeQox8/20/2022
like this?
RazorSharpFang
RazorSharpFang8/20/2022
Uhm, no?
RazorSharpFang
RazorSharpFang8/20/2022
Normal 128
The file is a standard file that has no special attributes. This attribute is valid only if it is used alone. Normal is supported on Windows, Linux, and macOS.
RazorSharpFang
RazorSharpFang8/20/2022
That's not a file
VeQox
VeQox8/20/2022
:HmmNoted: ......
VeQox
VeQox8/20/2022
right
RazorSharpFang
RazorSharpFang8/20/2022
You want Directory and without readonly
VeQox
VeQox8/20/2022
DirectoryInfo awd = new(folderPath)
                {
                    Attributes = FileAttributes.Directory
                };
RazorSharpFang
RazorSharpFang8/20/2022
Probably best to separate out that declaration and assignment with a try-catch sector
RazorSharpFang
RazorSharpFang8/20/2022
Because you may not succeeed changing its attributes
VeQox
VeQox8/20/2022
:HmmNoted:
VeQox
VeQox8/20/2022
so the attribute changed
VeQox
VeQox8/20/2022
from ReadOnly, Directory
to Directory
VeQox
VeQox8/20/2022
it still throws an error tho
RazorSharpFang
RazorSharpFang8/20/2022
Does it still say ReadOnly after you refresh it?
VeQox
VeQox8/20/2022
in the explorer?
RazorSharpFang
RazorSharpFang8/20/2022
No, call the Refresh() method
VeQox
VeQox8/20/2022
Nope
VeQox
VeQox8/20/2022
only directory
VeQox
VeQox8/20/2022
whats weird is that in the explorer interface it says its readonly
RazorSharpFang
RazorSharpFang8/20/2022
Is it still readonly if you run the app again?
RazorSharpFang
RazorSharpFang8/20/2022
What if you tried something like the following
DirectoryInfo directory = new DirectoryInfo(@"C:\my\directory");
DirectorySecurity security = directory.GetAccessControl();

security.AddAccessRule(new FileSystemAccessRule(@"MYDOMAIN\JohnDoe", 
                        FileSystemRights.Modify, 
                        AccessControlType.Deny));

directory.SetAccessControl(security);  
VeQox
VeQox8/20/2022
whats the identity on the FileSystemAccessRule constructor?
RazorSharpFang
RazorSharpFang8/20/2022
System.Security.AccessControl
VeQox
VeQox8/20/2022
:Hmm: so johndoe is the username? and how do i get the domain or do i just let it be empty so @"\user"
RazorSharpFang
RazorSharpFang8/20/2022
If it's a local user it's .\username
RazorSharpFang
RazorSharpFang8/20/2022
A domain user would be part of an organization like a workplace
VeQox
VeQox8/20/2022
:HmmNoted:
VeQox
VeQox8/20/2022
fails to parse the identy
VeQox
VeQox8/20/2022
my user name is what echo %username% gives me back?
VeQox
VeQox8/20/2022
tried both, %username% and the name visually on windows
RazorSharpFang
RazorSharpFang8/20/2022
Is this computer part of a domain?
VeQox
VeQox8/20/2022
sry fell asleep :pepecuke:
ContactFrequently Asked QuestionsJoin The DiscordBugs & Feature RequestsTerms & Privacy