Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Why does System.IO.File.Exists keep coming up false?

string profile = "\\" + txtProfileLoad.Text + ".txt";
profile = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + profile;

The variable profile is receiving the correct file path, but when I run it the File.Exists comes up false every time.

        if (System.IO.File.Exists(profile) == true)
        {
            System.IO.StreamReader profileReader;
            profileReader = new System.IO.StreamReader(profile);

            do
            {
                profileLevel = profileLevel + profileReader.ReadLine() + "\r\n";
            } while (profileReader.Peek() != -1);

            loadName(profileLevel);

            wordBeingUsed.finalWord = loadedName;

            Close();
        }
        else
        {
            MessageBox.Show("Invalid file name. Please try again.");
        }

There aren't any permissions stopping it from seeing the file. Any help with this would be appreciated. It's been driving me crazy.

like image 898
Greyhorne Avatar asked Dec 05 '25 03:12

Greyhorne


1 Answers

Is this a pre-existing file that you are trying to read? Or is this a new file that you are hoping to create? What is the value inside txtProfileLoad.Text, issue most likely is within this property.

Run a sanity check:

var profile = "mytestfile.txt";
var myFile = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), profile);
File.WriteAllText(myFile, "Testing file write");

if (File.Exists(myFile))
{
  // Access works.
}
else
{
  //Didn't work
}

If above code works, then it is most likely that the name you create from txtProfileLoad.Text is different from actual file on the drive. On the other hand, if this is a file that doesn't exist yet; then of course it would return false when you check Exists.

like image 106
loopedcode Avatar answered Dec 07 '25 17:12

loopedcode



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!