为什么文件访问被拒绝

Sea*_*dge 1 c# file

我有以下代码......

  • 检查文件夹是否存在
  • 如果存在,请检查文件是否存在
  • 如果文件存在,则从文件中读取所有行
  • 读取完所有行后,在消息框中显示该行的长度

码:

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");
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

每次运行应用程序(也使用Run as Administrator)时,都会继续调用以下行:

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

我该如何解决?

sta*_*ica 7

更换:

File.ReadAllLines(strPath);
Run Code Online (Sandbox Code Playgroud)

有:

File.ReadAllLines(strFile);
Run Code Online (Sandbox Code Playgroud)

原因:strPath表示目录.您试图将其内容读取为文件,但这显然不起作用.