c# -访问否定的路径- openFileDialog

本文关键字:路径 openFileDialog 访问 | 更新日期: 2023-09-27 18:10:58

我刚开始开发,我做了一个简单的应用程序,试图打开一个文件,应用程序返回我一个错误:"访问路径否定",但我是管理员,UAC被禁用,我是唯一的帐户,为什么它给我这个错误?

下面是我的代码:

private void button1_Click(object sender, EventArgs e)
    {
        Stream myStream = null;
        OpenFileDialog openFileDialog1 = new OpenFileDialog();
        openFileDialog1.InitialDirectory = "c:''";
        openFileDialog1.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*";
        openFileDialog1.FilterIndex = 2;
        openFileDialog1.RestoreDirectory = true;
        if (openFileDialog1.ShowDialog() == DialogResult.OK)
        {
            try
            {
                if ((myStream = openFileDialog1.OpenFile()) != null)
                {
                    using (myStream)
                    {
                        // Insert code to read the stream here.
                        string sourceCode = File.ReadAllText(Path.GetDirectoryName(openFileDialog1.FileName));
                        string colorizedSourceCode = new CodeColorizer().Colorize(sourceCode, Languages.Java);
                        textBox1.Text = colorizedSourceCode;
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("Error: Could not read file from disk. Original error: " + ex.Message);
            }
        }
    }

c# -访问否定的路径- openFileDialog

在我看来你是想在文件夹上打开一个流。

尝试替换

string sourceCode = File.ReadAllText(Path.GetDirectoryName(openFileDialog1.FileName))
与这个:

string sourceCode = File.ReadAllText(openFileDialog1.FileName)

打开流错误。

也许可以试试这样的东西?

private void button1_Click(object sender, EventArgs e)
    {            
            Stream myStream = null;
            OpenFileDialog openFileDialog1 = new OpenFileDialog();
            openFileDialog1.InitialDirectory = "c:''";
            openFileDialog1.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*";
            openFileDialog1.FilterIndex = 2;
            openFileDialog1.RestoreDirectory = true;
            if (openFileDialog1.ShowDialog() == DialogResult.OK)
            {
                try
                {
                    if ((myStream = openFileDialog1.OpenFile()) != null)
                    {
                        using (myStream)
                        {
                            string strfilename = openFileDialog1.FileName;
                            string filetext = File.ReadAllText(strfilename);
                            textBox1.Text = filetext;
                            button1.PerformClick();
                        }
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show("Error: Could not read file from disk. Original error: " + ex.Message);
                }
            }