c# ignore exceptions

Discussion in 'Software' started by supersav, Sep 10, 2009.

  1. supersav

    supersav Private E-2

    I am currently creating an application which searches through a directory and all its subdirectories for a certain file type and then if found displays this file type in a listbox.

    heres my problem however, there are certain directories/subdirectories which i do not have access to so when i run my application i get an UnauthorizedAccessException and so the application fails to complete the search, i was wondering if there was a way i could ignore this exception and just continue the search with the next directory.

    I would be very grateful for any help as i have been stuck for a while with no help, and i would appreciate some useful sample code if possible...here is the code i have at the moment....




    private void button1_Click(object sender, EventArgs e)

    {




    try
    {

    listBox1.Items.Clear();


    string[] temp = Directory.GetFiles(@"C:\", "*.drl", SearchOption.AllDirectories);




    for (int i = 0; i < temp.Length; i++)
    {
    listBox1.Items.Add(temp);
    }

    }




    catch (UnauthorizedAccessException)
    {
    throw;
    }

    }
     
  2. Wyatt_Earp

    Wyatt_Earp MajorGeek



    Just as a general rule, swallowing exceptions is a bad thing. You should at the very least write it out to a .log file or something.

    However, in your example, you need to put a try-catch around the statement that is throwing the exception. For example:

    Code:
    try
    {
    [INDENT]string[] temp = Directory.GetFiles(@"C:\", "*.drl", SearchOption.AllDirectories);[/INDENT]
    }
    catch (UnauthorizedAccessException)
    {
    [INDENT]// Log Error here[/INDENT]
    }
    Be aware that if the Directory.GetFiles() function is returning an exception, the list that it returns may or may not be valid. You'll need to research that on the MSDN to figure out what the output will be and how to handle it.
     

MajorGeeks.Com Menu

Downloads All In One Tweaks \ Android \ Anti-Malware \ Anti-Virus \ Appearance \ Backup \ Browsers \ CD\DVD\Blu-Ray \ Covert Ops \ Drive Utilities \ Drivers \ Graphics \ Internet Tools \ Multimedia \ Networking \ Office Tools \ PC Games \ System Tools \ Mac/Apple/Ipad Downloads

Other News: Top Downloads \ News (Tech) \ Off Base (Other Websites News) \ Way Off Base (Offbeat Stories and Pics)

Social: Facebook \ YouTube \ Twitter \ Tumblr \ Pintrest \ RSS Feeds