C#System.IO.File.Exists在Unity中不起作用

问题描述

我正在尝试在计算机上找到文件,以便将游戏的登录数据存储在该文件上。我有一个包含路径的字符串。

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

然后我稍后再讲:

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

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

我也尝试过换掉这个:

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

与此:

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

但是每次记录错误时。所以我不知道该怎么办。似乎其他人也有同样的问题。谢谢,如果您有答案。

解决方法

“文档”不是真实路径,它是Windows提供的“特殊文件夹”的便捷链接

来自https://docs.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
*/
,

Documents目录,而不是文件,因此与其检查File,不如检查Directory,例如:

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

请记住,如果要搜索文件,则path应该具有以下文件名和扩展名:

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