0

I have this method:

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; }));
            }
        }

The method first gets all the text files from the mydocuments directory and all its subdirectories:

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

The problem is for example I'm getting this exception:

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()

What should I do in this case ? I prefer for it to just pass over this directory and keep moving on to the next one.

Damon
  • 3,004
  • 7
  • 24
  • 28
DanielVest
  • 823
  • 4
  • 20
  • 39
  • 1
    You should comment out the `try-catch` block and see what the exact line the exception was thrown at. – King King Aug 10 '13 at 16:05
  • Or run a Debug build instead of a Release build - then maybe the exception would report the line number in your program where the exception occurred. – RenniePet Aug 10 '13 at 16:23
  • The problem here is likely going to be your attempt to create directories at the root level of the disk. Normal users do not have permission to do that. Why are you creating a `C:\temp` folder in the first place? What's wrong with the one Windows manages? And why are you hard-coding the path? Just so your program will blow up if it runs on someone's machine that doesn't have a drive `C:`? – Cody Gray - on strike Aug 10 '13 at 16:29
  • Related: [what is the best way to check in C# .NET if a directory has access to list files or a unauthorized access exception would rise](http://stackoverflow.com/q/18163472) – Cody Gray - on strike Aug 11 '13 at 10:03

1 Answers1

1

You should catch UnauthorizedAccessException and continue to loop otherwise:

for (int i = 0; i < textfiles.Length; i++)
{
    try
    {
       // YOUR CODE HERE
    }
    catch(UnauthorizedAccessException)
    {
       // DO NOTHING HERE
    }
}
Cody Gray - on strike
  • 239,200
  • 50
  • 490
  • 574
Rohit Vats
  • 79,502
  • 12
  • 161
  • 185
  • That seems like it would work, but I still wonder if there should be a better solution that manually checks permissions ahead of time. – Katana314 Aug 10 '13 at 16:15