Search code examples
c#visual-studioopenfiledialogaccess-denied

C# - Access negated to path - openFileDialog


I'm new to developing, I make a simply app to try to open a file the app return me an error: "access to the path negated" but I'm administrator, UAC is disabled and I'm the only account, why did it give me this error?

Here my code:

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

Solution

  • Looks to me like you're trying to open a stream on a folder.

    Try replacing this

    string sourceCode = File.ReadAllText(Path.GetDirectoryName(openFileDialog1.FileName))
    

    with this:

    string sourceCode = File.ReadAllText(openFileDialog1.FileName)