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

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

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

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

4

3 回答 3

2

这是您尝试读取的预先存在的文件吗?或者这是您希望创建的新文件?里面的值是什么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与驱动器上的实际文件不同。另一方面,如果这是一个尚不存在的文件;那么当你检查 Exists 时它当然会返回 false。

于 2013-10-29T05:53:01.503 回答
0

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

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

还要检查您是否可以使用文件打开方法而不是File.Exist.

于 2013-10-29T05:33:55.090 回答
0

根据MSDN

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

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

于 2013-10-29T05:43:56.273 回答