First time using asking a question on stackoverflow and I am also a beginner. I have written this code to check if multiple directories exist within my program. I need help making less verbose. It is very repetitive code that works but I feel like it is using too many words and if statements to do a simple task.
Here is the code:
string destPath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
string movedPath = destPath + @"\MyfolderTest";
string destPath2 = Environment.GetFolderPath(Environment.SpecialFolder.MyMusic);
string movedPath2 = destPath + @"\MyfolderTest";
string destPath3 = Environment.GetFolderPath(Environment.SpecialFolder.MyVideos);
string movedPath3 = destPath + @"\MyfolderTest";
string destPath4 = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
string movedPath4 = destPath + @"\MyfolderTest";
string destPath5 = Environment.GetFolderPath(Environment.SpecialFolder.MyPictures);
string movedPath5 = destPath + @"\MyfolderTest";
string destPath6 = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile);
string movedPath6 = destPath + @"\MyfolderTest";
if (!Directory.Exists(movedPath))
{
}
else
{
}
if (!Directory.Exists(movedPath2))
{
}
else
{
}
if (!Directory.Exists(movedPath3))
{
}
else
{
}
if (!Directory.Exists(movedPath4))
{
}
else
{
}
if (!Directory.Exists(movedPath5))
{
}
else
{
}
if (!Directory.Exists(movedPath6))
{
}
else
{
}
(Note: I am here assuming that you actually wanted to alternate which
destPaththat is being referred to in yourmovedPath*values; i.e. thatstring movedPath2 = destPath + @"\MyfolderTest";should rather bestring movedPath2 = destPath2 + @"\MyfolderTest";, and so on.)First, I'd identify what actually changes for each repeated code snippet. That may be easier to see if you visualize or edit the order of your logic from:
to
You observe that each repeated part comprises a
destPath*variable, amovedPath*variable and anif/elseloop that considers themovedPath*variable.You also observe that what actually changes is the input parameter for the
Environment.GetFolderPath( )method; i.e.Environment.SpecialFolder.MyDocumentsandEnvironment.SpecialFolder.MyMusic.By collecting all the possible input parameters for the
Environment.GetFolderPath( )method, e.g. in an array or a list, you can iterate over the input parameters in aforeachloop. Then, theforeachloop can contain your logic, and you will only need to define it once:As a last improvement, I'd recommend you to move the
@"\MyfolderTest"value outside the loop. It's better practice not to hard-code strings inside your logic. It may be defined as a constant in your class, or be a variable that is populated from user input.The end result may look like this: