简体   繁体   English

如何避免未经授权的访问异常?

[英]how to avoid unauthorized access exception?

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. 所以我正在做的是获取音乐和电影的列表,并将属性放入sql数据库,但我希望它搜索用户文件中的所有目录。 due to the appdata im getting a 由于appdata我得到了

System.UnauthorizedAccessException was unhandled. System.UnauthorizedAccessException未处理。

how can i avoid this? 我怎么能避免这个? the error is where it is pulling all files from the user folder Josh. 错误是它从用户文件夹Josh中提取所有文件的位置。

Some files are system files (such as the ones in User folder as in your case like AppData etc). 有些文件是系统文件(例如用户文件夹中的文件,如AppData等)。 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 我建议你看一下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 https://msdn.microsoft.com/en-us/library/0d005ted(v=vs.90).aspx

Use Directory.EnumerateDirectories in order to access each folder one at a time and either ignore or log the ones that throw exceptions. 使用Directory.EnumerateDirectories以便一次访问一个文件夹,并忽略或记录引发异常的文件夹。 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. 如果您想知道如何获得目录的权限,那就是您的用户帐户权限。

You should be using the enum Environment.SpecialFolder . 您应该使用枚举Environment.SpecialFolder
use Environment.GetFolderPath(Environment.SpecialFolder.MyMusic ) for music folder or Environment.GetFolderPath(Environment.SpecialFolder.UserProfile ) + @"\\Downloads"; 使用Environment.GetFolderPath(Environment.SpecialFolder.MyMusic )作为音乐文件夹或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. 具体来说,这是因为理想情况下,您无法访问用户文件夹中Windows资源管理器本身的所有文件夹和子文件夹。 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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM