C# 为什么System.IO.File.Exist总是出现错误

本文关键字:错误 Exist 为什么 System IO File | 更新日期: 2023-09-27 18:37:25

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

变量配置文件正在接收正确的文件路径,但是当我运行它时,File.Exists 每次都出现 false。

        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.");
        }

没有任何权限阻止它查看文件。任何这方面的帮助将不胜感激。这让我发疯了。

C# 为什么System.IO.File.Exist总是出现错误

这是您尝试读取的预先存在的文件吗?或者这是您希望创建的新文件?txtProfileLoad.Text里面的值是什么,问题很可能在此属性内。

运行健全性检查:

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
}

如果上面的代码有效,那么您从txtProfileLoad.Text创建的名称很可能与驱动器上的实际文件不同。另一方面,如果这是一个尚不存在的文件;那么当您检查存在时,它当然会返回 false。

您可以使用字符串变量并将文件名传递给它:

string tempFile = txtProfileLoad.Text;
string profile = @"C:'temp'tempfile.txt";

另请查看是否可以使用文件打开方法而不是File.Exist

根据 MSDN:

如果调用方具有所需的权限并且路径包含现有文件的名称,则为 true;否则false。此方法也 如果路径为"无"、路径无效或长度为零,则返回 false。 字符串。如果调用方没有足够的权限来读取 指定的文件,不会引发异常,并且该方法返回 false 不管路径是否存在。

您是否尝试过以管理员身份运行?尝试在Visual Studio图标上"右键单击"并选择"以管理员身份运行",看看是否仍然遇到相同的行为。