0

Why does my code won't trigger the else condition? If I can't locate my file it won't prompt, but if it locate it prompts.

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

    private void button1_Click(object sender, EventArgs e)
    {
        string path = @"C:\Personal Folders\";

        string[] files = Directory.GetFiles(path,
            "*3.zip*",   //set sa batch
            SearchOption.AllDirectories);


        // Display all the files.

        foreach (string file in files)
        {
            bool exist = File.Exists(file);

            if (exist == true) 
            { 
              MessageBox.Show("File Located : " + Convert.ToString(file));
            }
            else
            {
                MessageBox.Show("File Cant Locate :");
            }

        }
    }
2
  • 1
    GetFiles returns the file names that it matches with the given pattern (it means the files are physically exist) and you are simply iterating the collection returned by GetFiles. In this case your code will never go into the else part. Commented Feb 28, 2019 at 4:10
  • is there anyway code that can search a file in the path ? if not exist it will prompt does file not located and some file thats located will proceed ? thanks in advance Commented Feb 28, 2019 at 4:13

1 Answer 1

1

In the code

string[] files = Directory.GetFiles(path,
            "*3.zip*",   //set sa batch
            SearchOption.AllDirectories);

this returns the files which are present in that directory with the matching pattern, so checking for file exists does not make sense anyways and hence your else is never executing.

Sign up to request clarification or add additional context in comments.

3 Comments

is there anyway code that can search a file in the path ? if not exist it will prompt does file not located and some file thats located will proceed ? thanks in advance
File.Exists is the method which accepts a file path and returns true if file exists else false.
@user3446835 Please mark this as answer if this is solving your problem. Happy coding!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.