【问题标题】:How can i avoid or pass over a directory that is access denied?我怎样才能避免或跳过被拒绝访问的目录?
【发布时间】:2013-08-10 16:01:42
【问题描述】:

我有这个方法:

private void SearchForDoc()
        {
            try
            {
                outputtext = @"c:\temp\outputtxt";
                outputphotos = @"c:\temp\outputphotos";
                temptxt = @"c:\temp\txtfiles";
                tempphotos = @"c:\temp\photosfiles";
                if (!Directory.Exists(temptxt))
                {
                    Directory.CreateDirectory(temptxt);
                }
                if (!Directory.Exists(tempphotos))
                {
                    Directory.CreateDirectory(tempphotos);
                }
                if (!Directory.Exists(outputtext))
                {
                    Directory.CreateDirectory(outputtext);
                }
                if (!Directory.Exists(outputphotos))
                {
                    Directory.CreateDirectory(outputphotos);
                }
                t = Environment.GetEnvironmentVariable("UserProfile") + "\\documents";
                //string[] extensionstxt = { "*.txt" };//Directory.GetFiles(t, "*.txt", SearchOption.AllDirectories);
                //var textfiles = extensionstxt.SelectMany(x => Directory.GetFiles(t, x));
                string[] textfiles = Directory.GetFiles(t, "*.txt", SearchOption.AllDirectories);
                for (int i = 0; i < textfiles.Length; i++)
                {

                    //File.Copy(txtfiles[i], temptxt + "\\" + Path.GetFileName(txtfiles[i]),true);
                    FileInfo fi = new FileInfo((textfiles[i]));
                    DirectoryInfo d = new DirectoryInfo(temptxt);
                    long dirSize = DirSize(d);
                    //if copying the file would take the directory over 50MB then don't do it
                    if ((dirSize + fi.Length) <= 8388608)//7340032)//52428800)
                        fi.CopyTo(temptxt + "\\" + fi.Name, true);
                    else
                        break;

                }
                Compressions("textfiles.zip", temptxt, outputtext);


                s = Environment.GetEnvironmentVariable("UserProfile") + "\\Pictures";
                string[] extensions = { "*.bmp", "*.jpg", "*.png", "*.gif" };//add extensions you want to filter first
                var photosfiles = extensions.SelectMany(x => Directory.GetFiles(s, x));
                //string[] photosfiles = Directory.GetFiles(s, "*.*", SearchOption.AllDirectories);
                for (int i = 0; i < photosfiles.ToArray().Length; i++)
                {
                    FileInfo fi = new FileInfo((photosfiles.ToArray()[i]));
                    DirectoryInfo d = new DirectoryInfo(tempphotos);
                    long dirSize = DirSize(d);
                    //if copying the file would take the directory over 50MB then don't do it
                    if ((dirSize + fi.Length) <= 8388608)//7340032)//52428800)
                        fi.CopyTo(tempphotos + "\\" + fi.Name, true);
                    else
                        break;
                }
                Compressions("photofiles.zip", tempphotos, outputphotos);

            }
            catch (Exception err)
            {
                Logger.Write("There was an exception" + Environment.NewLine + err);
                SendEmail.BeginInvoke(new Action(() => { SendEmail.Enabled = true; }));
            }
        }

该方法首先从 mydocuments 目录及其所有子目录中获取所有文本文件:

t = Environment.GetEnvironmentVariable("UserProfile") + "\\documents";

问题是例如我遇到了这个异常:

10/08/2013--18:54 ==> First Time The Log File Was Created

10/08/2013--18:54 ==> ***** OPERATION STARTED *****
10/08/2013--18:54 ==> ***** Copied The Windowsupdate Log File *****
10/08/2013--18:54 ==> ***** Drivers Text File Have Been Created *****
10/08/2013--18:54 ==> ***** Hosts File Have Been Created *****
10/08/2013--18:54 ==> There was an exception
System.UnauthorizedAccessException: Access to the path 'C:\Users\Simbalip\documents\My Music\' is denied.
   at System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath)
   at System.IO.FileSystemEnumerableIterator`1.AddSearchableDirsToStack(SearchData localSearchData)
   at System.IO.FileSystemEnumerableIterator`1.MoveNext()
   at System.Collections.Generic.List`1..ctor(IEnumerable`1 collection)
   at System.IO.Directory.InternalGetFileDirectoryNames(String path, String userPathOriginal, String searchPattern, Boolean includeFiles, Boolean includeDirs, SearchOption searchOption)
   at System.IO.Directory.InternalGetFiles(String path, String searchPattern, SearchOption searchOption)
   at Diagnostic_Tool_Blue_Screen.Form1.SearchForDoc()

在这种情况下我该怎么办?我更喜欢它跳过这个目录并继续前进到下一个。

【问题讨论】:

  • 您应该注释掉 try-catch 块并查看引发异常的确切行。
  • 或者运行调试版本而不是发布版本 - 那么异常可能会报告您程序中发生异常的行号。
  • 这里的问题可能是您尝试在磁盘的根级别创建目录。普通用户无权执行此操作。你为什么首先创建一个C:\temp 文件夹? Windows 管理的那个有什么问题?为什么要对路径进行硬编码?如果你的程序在没有驱动器C:的机器上运行,你的程序就会崩溃?

标签: c# winforms


【解决方案1】:

你应该抓住UnauthorizedAccessException,否则继续循环:

for (int i = 0; i < textfiles.Length; i++)
{
    try
    {
       // YOUR CODE HERE
    }
    catch(UnauthorizedAccessException)
    {
       // DO NOTHING HERE
    }
}

【讨论】:

  • 这似乎可行,但我仍然想知道是否应该有更好的解决方案,提前手动检查权限。
猜你喜欢
  • 2011-09-08
  • 1970-01-01
  • 2018-12-08
  • 2013-07-24
  • 1970-01-01
  • 1970-01-01
  • 2023-03-10
  • 2013-10-08
  • 1970-01-01
相关资源
最近更新 更多