Search code examples
c#if-statementfilepathfilenotfoundexception

C# - Using File.Exists, when file DOESN'T exist does not run the last else statement


Super new to C#. I'm having an input get split and then find an ID from the pointsTarget var.

When the file DOES exist, it seems that the line

else if (File.Exists(filePath+userId+txt))
   returns true;

because it runs just fine and sets the argument "addPointsCompleted" to TRUE. It works just how I would expect. But when the file does NOT exist, I want it to return false and run the last else statement:

CPH.SetArgument("missing", "True");

and set "missing" to TRUE.

I feel like there is something wrong with the way I put in the if/else if/else statement because I get an error :

"System.IO.FileNotFoundException: Could not find file 'E:\Users\Troy\Documents\Stuff\PointNames\Test.txt'.

using System;
using System.IO;

public class CPHInline
{
    public bool Execute()
    {
        string rawInput = args["rawInput"].ToString();
        string[] split= rawInput.Split('+');
        var pointsTarget = split[0].ToString();
        var addPoints = split[1].ToString();
        CPH.LogInfo($"pointsTarget is {pointsTarget}");
        CPH.LogInfo($"addPoints is {addPoints}");
        var user = args["user"].ToString();
        CPH.SetArgument("pointsTarget", pointsTarget);
        string userPath = @"E:/Users/Troy/Documents/Stuff/PointNames/";
        string filePath = @"E:/Users/Troy/Documents/Stuff/PointIDs/";
        string txt = ".txt";
        var userId = File.ReadAllText(userPath+pointsTarget+txt);
        CPH.LogInfo($"userId is {userId}");

        if (user == pointsTarget)
        {
            CPH.SetArgument("corrupt", "True");
        }
        else if (File.Exists(filePath+userId+txt))
        {
            //DO THIS
            string fileName = filePath+userId+txt;
            string points = File.ReadAllText(fileName);
            int x = Convert.ToInt32(points);
            int y = Convert.ToInt32(addPoints);
            int sum = x + y;
            String newPoints;
            newPoints = sum.ToString();
            File.WriteAllText(fileName, newPoints);
            CPH.SetArgument("newPoints", newPoints);
            CPH.SetArgument("addPointsCompleted", "True");
        }
            
        else
        {
            //do this
            CPH.SetArgument("missing", "True");
        }

        return true;

     
    }
}

I tried looking around, but all the issues are from people where the file DOES exist and they can't find it. My problem is kind of the opposite.


Solution

  • I feel like there is something wrong with the way I put in the if/else if/else statement because I get an error "System.IO.FileNotFoundException: Could not find file 'E:\Users\Troy\Documents\Stuff\PointNames\Test.txt'.

    This is a good opportunity for you to start familiarizing yourself with using a debugger to step through the code and observe its behavior. Because the problem has nothing to do with your if structure. It's happening before your if block. Right here:

    var userId = File.ReadAllText(userPath+pointsTarget+txt);
    

    Look at the error message. It's trying to read a file in the "PointNames" folder. Which is in your userPath variable:

    string userPath = @"E:/Users/Troy/Documents/Stuff/PointNames/";
    

    Which is only ever used in that one line of code that tries to read a file. And File.ReadAllText will throw a FileNotFoundException if the file is not found.

    It seems you're already aware of how to check if a file exists. So why not apply that here? For example:

    var userId = string.Empty;
    if (File.Exists(userPath+pointsTarget+txt))
    {
        userId = File.ReadAllText(userPath+pointsTarget+txt);
    }
    else
    {
        // handle the error in some way
    }