Reputation: 25
I need to look if a path is available, but only at the runtime. So if my program has checked that the file doesn't exist, it sets the invalidPath bool to "true", so that it doesn't jump in the "File.Exists..." query again, as long the program runs.
The problem is: if I do it in that way like listed below, I see no possibility to avoid code redundancy. I need to show a message to inform the user about the missing file, but it isn't very elegant to use the same line(s) of code for both "if" cases.
private bool invalidPath = false
if (!invalidPath)
{
if (File.Exists(temp))
{
//do code
}
else
{
Show.MessageBox("no file found")
invalidPath = true
}
}
else
{
Show.Messagebox("no file found") /*<---thats redundant*/
}
I hope someone can give me an idea.
Upvotes: 0
Views: 1502
Reputation: 509
Try this:
bool invalidPath = false;
bool fileExistsflag = false;
if (!invalidPath)
{
if (File.Exists(temp))
{
//do code
fileExistsflag = true;
}
else
{
invalidPath = true;
}
}
if (!fileExistsflag || invalidPath)
{
MessageBox.Show("no file found");
}
Upvotes: 2
Reputation: 21
You cannot use a single boolean to hold both Information (Path checked and File exists). Thus you have to use a second boolean.
The pseudo-code would look like this:
bool valid = false;
bool checked = false;
if(!checked)
{
valid = File.Exists("bla");
checked = true;
}
if(!valid)
{
MessageBox("Path does not exist");
}
However, your strategy might have issues. For example a user might remove or rename the path while your program is running.
Upvotes: 0
Reputation: 663
is there a reason why you don't want to combine the boolean statements in a single if block?
i.e.
private bool invalidPath = false
if (!invalidPath && File.Exists(temp)) {
//do code
}
else {
Show.MessageBox("no file found")
invalidPath = true
}
Upvotes: 1