OpenFileDialog和UnauthorizedAccessException

时间:2015-10-29 01:09:00

标签: c# openfiledialog unauthorizedaccessexcepti

我正在开发一种工具,将.fbx模型和用户输入处理成单个文件,以便在游戏中使用。用户按下“导入模型”按钮时的代码如下所示,并且对于每个按钮都类似:

private void E_ImportModelButton_Click_1(object sender, EventArgs e)
{
    E_model = null; // byte array where model is stored
    E_SelectedFileLabel.Text = "No Model Selected"; // label on form
    OpenFileDialog ofd = new OpenFileDialog();
    ofd.Filter = "FBX Model (.fbx)|*.fbx";
    ofd.Multiselect = false;
    if (ofd.ShowDialog() == DialogResult.OK)
    {
        // adjusts variables for game file
        string s = Path.GetDirectoryName(ofd.FileName);
        E_model = File.ReadAllBytes(s);
        E_SelectedFileLabel.Text = "File Selected: " + ofd.FileName;
    }
}

问题是,每当我点击OK,就会出现UnauthorizedAccessException。我尝试从C:\Users\Owner\Downloads以及C:\Users\Owner\DesktopC:\驱动器本身导入文件,但它仍然会发生。我可以添加哪些代码来访问这些(和其他)文件夹?

2 个答案:

答案 0 :(得分:1)

您正尝试通过用于从文件中读取的方法从目录中读取:

string s = Path.GetDirectoryName(ofd.FileName);
E_model = File.ReadAllBytes(s);

将其替换为:

E_model = File.ReadAllBytes(ofd.FileName);

答案 1 :(得分:1)

您无法准备目录,您必须阅读文件:

string s = Path.GetDirectoryName(ofd.FileName);
E_model = File.ReadAllBytes(s);

尝试在此处添加文件名