Search code examples
c#file-exists

Hot to search for the existence of 2 xml files in one if statement?


As the title suggests i am trying to write an if else statement that searches for the existance of 2 xml files ( and if they do exist the user will have the option of which one to load) but currently all i can do is an else if statement that assumes there is only one of the two files,

private void yourCharacterInformationButton_Click(object sender, RoutedEventArgs e)
    {
        // This will search for and load the saved name class from the relevant Xml file.

below is my code Current code

i couldnt find an answer allready on here after trawling through for a while, if someone could provide an answer that would be brilliant, again all i want to do is to search for the existence of 2 files in the same if statement such as

if(file.exists("ClassData.xml", "UserClassData.xml")
{
       messagebox.show("Which version do you want to load?").

Solution

  • You can write compound if statements by using the && operator.

    if (File.Exists("NameData.xml") && File.Exists("ClassData.xml"))
    {
        // Omitted for brevity...
    }
    

    Both sides would need to be true in order to execute. The System.IO.File class method for Exists only accepts a single string. You could write a method that takes any number of file paths and call into this method like so (a little Linq):

    private bool AllFilesExist(params string[] paths)
    {
        return paths != null && paths.All(File.Exists);
    }
    

    Then you could invoke this method from within your call like so:

    private void yourCharacterInformationButton_Click(object sender, RoutedEventArgs e)
    {
        if (AllFilesExist("NameData.xml", "ClassData.xml"))
        {
            // Omitted for brevity...
        }
    }