Home > Enterprise >  Weird behaviour on File.Exists() on C# .NET Framework 4.8
Weird behaviour on File.Exists() on C# .NET Framework 4.8

Time:09-28

I am currently working on a program on WinForms on Visual Studio Community 2022. The program has to check if a file exists on the install directory using File.Exists(), but there is a really weird behaviour that I cannot seem to solve: when debugging (and even running it in the Release mode) the application on VS2022, the value the method returns is false (which is right, because the file doesn't exist at the moment of running the method), but when installing the application, it says the file exists, even when it doesn't, and it can even read the content of that file. Here's the code:

private static string AppPath = $@"{Environment.GetFolderPath(Environment.SpecialFolder.ProgramFilesX86)}\eMA\eMA";

public async Task<JArray> GetVersionsJArrayFromComputer()
        {
            JArray versionsJArray = new JArray();
            await Task.Run(async () =>
            {
                string path = AppPath;
                if (!await CheckIfVersionJSONFileExists())
                {
                    if (!await IsRunningAsAdmin())
                    {
                        await RunAsAdmin();
                        Environment.Exit(0);
                    }
                    else
                    {
                        await SaveVersionJSONFile(await SetVersionsJArrayFromComputer());
                    }
                }
                string versionFilePath = $@"{path}\version.json";
                string versionFile = File.ReadAllText(versionFilePath);
                versionsJArray = (JArray)JsonConvert.DeserializeObject(versionFile);
            });
            return versionsJArray;
        }

private static async Task<bool> CheckIfVersionJSONFileExists()
        {
            bool fileExists = false;
            await Task.Run(() =>
            {
                string path = AppPath;
                string fileName = $@"{path}\version.json";
                fileExists = File.Exists(fileName);
            });
            return fileExists;
        }

I created some MessageBoxes to try to debug the application when it is already installed, and this is what it says: Image

This is the content that it reads from the file (and, in theory, if the file doesn't exist, it shouldn't have any content): Image

And I don't really know why would it say the file doesn't exist when debugging and then it exists when installed. Any help would be really appreciated.

CodePudding user response:

Thanks to all the people who commented. It turned out to be a UAC virtualization issue (which I didn't know existed at that time).

  • Related