SearchForKnowledge
SearchForKnowledge

Reputation: 3751

Why file access is denied

I have the following code which...

Code:

private void button2_Click(object sender, EventArgs e)
{
    strPath = @"C:\QRXS";
    string strFile = @"C:\QRXS\download.lst";
    if (Directory.Exists(strPath))
    {
        try
        {
            if (File.Exists(strFile))
            {
                try
                {
                    ln = File.ReadAllLines(strPath);
                }
                catch (Exception ex)
                {
                    // inform user or log depending on your usage scenario
                    MessageBox.Show(ex.Message, "FILE ACCESS");
                }

                if (ln != null)
                {
                    MessageBox.Show(ln.Length + "");
                    // do something with lines
                }
            }
        }
        catch (Exception ce)
        {
            MessageBox.Show(ce.Message, "FOLDER ACCESS");
        }
    }
}

Everytime I run the application (used Run as Administrator as well), the following line keeps being invoked:

MessageBox.Show(ex.Message, "FILE ACCESS");

How can I fix it?

Upvotes: 1

Views: 189

Answers (2)

MRebai
MRebai

Reputation: 5474

You need to use :

File.ReadAllLines(strFile);

Upvotes: 2

Replace:

File.ReadAllLines(strPath);

with:

File.ReadAllLines(strFile);

Reason: strPath denotes a directory. You're trying to read its contents as if it were a file, and that obviously won't work.

Upvotes: 7

Related Questions