GraniteSOS
GraniteSOS

Reputation: 49

C# System.IO.File.Exists does not work in Unity

I am trying to locate a file on my computer so I can store my game's login data on that certain file. I have a string that contains the path.

public string path = "C:/Users/DevelopVR/Documents";
//DevelopVR is my username

Then I have this later on:

if (System.IO.File.Exists(path))
{
Debug.Log("Path exists on this computer");
}

else
{
Debug.LogWarning("Path does NOT exist on this computer");
}

I have also tried swapping out this:

else
{
Debug.LogWarning("Path does NOT exist on this computer");
}

With this:

else if (!System.IO.File.Exists(path))
{
Debug.LogWarning("Path does NOT exist on this computer");
}

But every time it logs the error. So I don't know what to do. It seems like other people are having the same problem. Thanks, If you have the answer.

Upvotes: 2

Views: 3037

Answers (2)

Lotan
Lotan

Reputation: 4283

Documents is a Directory, not a File, so instead of checking for File, check for Directory like:

if(File.Exists(path))
{
    // This path is a file
    ProcessFile(path);
}
else if(Directory.Exists(path))
{
    // This path is a directory
    ProcessDirectory(path);
}

Remember that if you want to search for a File, your path should have the file name and extension like:

public string path = @"C:/Users/DevelopVR/Documents/MyFile.txt";

Upvotes: 4

Immersive
Immersive

Reputation: 1704

"Documents" is not a real path, it's a convenience link to the 'special folder' that Windows provides.

From https://learn.microsoft.com/en-us/dotnet/api/system.environment.specialfolder?view=netcore-3.1

// Sample for the Environment.GetFolderPath method
using System;

class Sample
{
    public static void Main()
    {
        Console.WriteLine();
        Console.WriteLine("GetFolderPath: {0}", Environment.GetFolderPath(Environment.SpecialFolder.System));
    }
}
/*
This example produces the following results:

GetFolderPath: C:\WINNT\System32
*/

Upvotes: 1

Related Questions