以下是我的代码。
//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();
}
所以我正在做的是获取音乐和电影列表并将那里的属性放入 sql 数据库,但我希望它搜索用户文件中的所有目录。由于 appdata 我得到了一个
System.UnauthorizedAccessException 未处理。
我怎样才能避免这种情况?错误是它从用户文件夹 Josh 中提取所有文件。