简体   繁体   中英

C# issue maintaining some code

I have the following code I am trying to "fix"

foreach (System.IO.DirectoryInfo dir in source.GetDirectories())
    CopyFilesRecursively(dir, target.CreateSubdirectory(dir.Name),safeFileNames);
foreach (System.IO.FileInfo file in source.GetFiles())
    if (safeFileNames)
    {
    }

The code goes on to do more, but I noticed that the foreach loops don't contain any {} brackets...

Which of the following will fix this :

foreach (System.IO.DirectoryInfo dir in source.GetDirectories())
{
    CopyFilesRecursively(dir, target.CreateSubdirectory(dir.Name),safeFileNames);
}
foreach (System.IO.FileInfo file in source.GetFiles())
{
    if (safeFileNames)
    {
    }
}

or..........

foreach (System.IO.DirectoryInfo dir in source.GetDirectories())
{
    CopyFilesRecursively(dir, target.CreateSubdirectory(dir.Name),safeFileNames);
    foreach (System.IO.FileInfo file in source.GetFiles())
        if (safeFileNames)
        {
        }
}

Once I've fixed the outerloop I can then look at cleaning up the inner loop.

On a side note, nothing more annoying to me than seeing code logic not containing explicit markings of the bounds of the control. You see a lot of this in JS code samples on the web.

Thanks.

First option is right:

foreach (System.IO.DirectoryInfo dir in source.GetDirectories())
{
    CopyFilesRecursively(dir, target.CreateSubdirectory(dir.Name),safeFileNames);
}

foreach (System.IO.FileInfo file in source.GetFiles())
{
    if (safeFileNames)
    {
    }
}

If your block statement doesn't contains any {} , just next line will be included.

The 2nd item is just plain wrong, as it will change the meaning of your code. The 1st item will work, but since braces are not required by the language and you are bothered by their absense, you probably want this:

foreach (System.IO.DirectoryInfo dir in source.GetDirectories())
{
     CopyFilesRecursively(dir, target.CreateSubdirectory(dir.Name),safeFileNames );
}
foreach (System.IO.FileInfo file in source.GetFiles())
{
    if (safeFileNames)
    {
    }
}

Edit
Now that you changed your question, it's definitely the first option.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM