开发者

C# File Permission Exclusion

开发者 https://www.devze.com 2023-03-21 22:12 出处:网络
I was wondering if there is a way to solve the issue I have with this code: DriveInfo[] dDrives = DriveInfo.GetDrives();

I was wondering if there is a way to solve the issue I have with this code:

DriveInfo[] dDrives = DriveInfo.GetDrives();
foreach(DriveInfo dDrive in dDrives)
{
    try
    {
        string sDrive = dDrive.ToString();
        string[] sSearch = Directory.GetFiles(sDrive, sFile, SearchOption.AllDirectories);
        foreach(string sResult in sSearch)
        {
            textBox2.Text = sResult + Environment.NewLine;
        }
    }
    catch
    {
    }
}

When it comes across a 开发者_如何学Pythonfile that isn't accessible because of permissions, it will goto the catch and end. What I need it to do is if it comes across a file it can't access, go back to the try block and continue searching. Any help is much appreciated, thanks!


EDIT: Removed original answer as incorrect.

See: UnauthorizedAccessException cannot resolve Directory.GetFiles failure for some suggested resolutions to your problem.


The code you have should work, though you really should rethink your logic, using exceptions for flow control is plain wrong.

This will work, though not best practice:

string sDrive = dDrive.ToString();
try
{
   string[] sSearch = Directory.GetFiles(sDrive, sFile, SearchOption.AllDirectories);
}
catch {}

foreach(string sResult in sSearch)
{
    textBox2.Text = sResult + Environment.NewLine;
}

Where exactly are you accessing files? I only see a call to list file names (Directory.GetFiles), and listing of the file names returned.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号