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.
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.