how to avoid unauthorized access exception?

5.2k views Asked by At

The following is my code.

 //string[] directories; 
        List<string> dirs = new List<string>(Directory.EnumerateDirectories("C:\\Users\\Josh"));
        //string[] Files;

        //directories = Directory.GetDirectories(@"C:\Users\Josh\", "*", SearchOption.AllDirectories);

        SqlConnection myConn = new SqlConnection("Server=Josh-PC;database=Music;User ID=Josh; Password=Climber94; Trusted_Connection=True;");

        string removeText = "Delete from Music.dbo.SongNamesAndInfo";
        SqlCommand RemoveEntry = new SqlCommand(removeText, myConn);

        myConn.Open();

        RemoveEntry.ExecuteNonQuery();

        myConn.Close();

        //for (int d = 0; d < directories.Length; d++)
        foreach (var dir in dirs)
        {                            
            List<string> files = new List<string>(Directory.EnumerateFiles(dir));

            foreach (var file in files)
            {

                FileInfo oFileInfo = new FileInfo(file);

                myConn.Open();

                string cmdText = "Insert INTO Music.dbo.SongNamesAndInfo " +
                        "(Name,dtCreationTime,Extension,Length,DirectoryName)" +
                        "VALUES(@Name,@dtCreationtime,@Extension,@Length,@DirectoryName)";

                SqlCommand addCmd = new SqlCommand(cmdText, myConn);                    
                DateTime dtCreationTime = oFileInfo.CreationTime;

                addCmd.Parameters.AddWithValue("@Name", oFileInfo.Name);                                       
                addCmd.Parameters.AddWithValue("@dtCreationtime", dtCreationTime);                    
                addCmd.Parameters.AddWithValue("@Extension", oFileInfo.Extension);                    
                addCmd.Parameters.AddWithValue("@Length", oFileInfo.Length.ToString());                    
                addCmd.Parameters.AddWithValue("@DirectoryName", oFileInfo.DirectoryName);

                if (oFileInfo.Extension.ToLower() == ".mp3" || oFileInfo.Extension.ToLower() == ".avi" ||                    
                    oFileInfo.Extension.ToLower() == ".mkv" || oFileInfo.Extension.ToLower() == ".m4a" ||                        
                    oFileInfo.Extension.ToLower() == ".aac" || oFileInfo.Extension.ToLower() == ".wav" ||                        
                    oFileInfo.Extension.ToLower() == ".mpa" || oFileInfo.Extension.ToLower() == ".wma" ||                        
                    oFileInfo.Extension.ToLower() == ".flv" || oFileInfo.Extension.ToLower() == ".m4v" ||                        
                    oFileInfo.Extension.ToLower() == ".mpg" || oFileInfo.Extension.ToLower() == ".mov" ||                        
                    oFileInfo.Extension.ToLower() == ".wmv" || oFileInfo.Extension.ToLower() == ".mp4")                        
                {                            
                    addCmd.ExecuteNonQuery();
                }

                myConn.Close();                    
            }         

so what im doing is taking a list of music and movies and placing there properties into a sql data base but i want it to search all the directory's in the user file. due to the appdata im getting a

System.UnauthorizedAccessException was unhandled.

how can i avoid this? the error is where it is pulling all files from the user folder Josh.

3

There are 3 answers

0
Aaron Anodide On

Use Directory.EnumerateDirectories in order to access each folder one at a time and either ignore or log the ones that throw exceptions. This way you'll get as much as you can.

If you want to know how to get permission to a directory, that's a matter of your user account's permissions.

1
Akshita On

Some files are system files (such as the ones in User folder as in your case like AppData etc). you can either request permission or ignore them

        FileIOPermission f = new FileIOPermission(PermissionState.Unrestricted);
        f.AllLocalFiles = FileIOPermissionAccess.Read;
        try
        {
            f.Demand();
            //your code for processing files
        }
        catch (SecurityException s)
        {
            //cannot get permissions for files.got exception
            Console.WriteLine(s.Message);
        }

i suggest you to take a look at Code Access Security https://msdn.microsoft.com/en-us/library/930b76w0(v=vs.85).aspx

https://msdn.microsoft.com/en-us/library/0d005ted(v=vs.90).aspx

1
Dhanilan On

You should be using the enum Environment.SpecialFolder.
use Environment.GetFolderPath(Environment.SpecialFolder.MyMusic ) for music folder or Environment.GetFolderPath(Environment.SpecialFolder.UserProfile ) + @"\Downloads"; etc specifically.This is because ideally you won't get access to all folders and sub folders in the Windows explorer itself in the user folders. That is where it throws the exception.
so your code would be something like this

        string[] directories;
        string[] Files;
        string folder = Environment.GetFolderPath(Environment.SpecialFolder.MyMusic ) ;
        directories = Directory.GetDirectories(folder);