Unity中System.IO.File.Exists无法正常工作的问题求助
Hey there! I see exactly what's going on here—you're hitting a super common gotcha with .NET's file system checks. Let's break it down and get this fixed:
The Root Problem
You’re using System.IO.File.Exists() to verify that your Documents folder exists, but this method is built to check for files, not directories. No matter if your Documents folder is actually present or not, File.Exists() will always return false for a folder path. That’s why your warning keeps popping up every time you run the code.
The Simple Fix
Swap out File.Exists() with System.IO.Directory.Exists()—this is the correct method to check if a folder path exists. Here’s your updated code:
public string path = "C:/Users/DevelopVR/Documents"; if (System.IO.Directory.Exists(path)) { Debug.Log("Path exists on this computer"); } else { Debug.LogWarning("Path does NOT exist on this computer"); }
A Couple Extra Tips
- That
else if (!System.IO.File.Exists(path))version you tried is totally redundant. Theelseclause already covers all cases where the initialifcondition fails, so adding that extra check doesn’t change anything (plus it still uses the wrong method!). - If you later need to check for a specific file inside that Documents folder (like your game’s login data file), use
Path.Combine()to safely merge the folder path with the filename (this handles slashes correctly across different operating systems) and then useFile.Exists()on the full file path:string loginDataPath = System.IO.Path.Combine(path, "game_login_data.txt"); if (System.IO.File.Exists(loginDataPath)) { Debug.Log("Login data file found!"); } else { Debug.LogWarning("Login data file missing."); }
That should resolve your issue once and for all!
内容的提问来源于stack exchange,提问作者GraniteSOS

