C#未经授权的访问异常

时间:2015-06-16 19:11:43

标签: c#

当我尝试打开文件时,我收到了一个未经授权的访问异常

 public Form1()
    {
        InitializeComponent();
    }

    private void button1_Click(object sender, EventArgs e)
    {
        short numberOfLines = Int16.Parse(textBox1.Text);
        webBrowser = new WebBrowser[numberOfLines];
        if (!Directory.Exists(logPath))
        {
            System.IO.Directory.CreateDirectory(logPath);
        }
        for (short i = 0; i < numberOfLines; i++)
        {
            System.IO.StreamWriter file = new System.IO.StreamWriter(logPath);
            runBrowserThread(i);
        }
    }  

它说,对路径的访问被拒绝了。问题可能在哪里?

1 个答案:

答案 0 :(得分:0)

该代码正在尝试写入目录,就像它是一个文件一样。

尝试使用引用目录的文件路径创建文件时,系统会向您显示UnauthorizedAccessException

if (!Directory.Exists(logPath))
{
    System.IO.Directory.CreateDirectory(logPath);
}
for (short i = 0; i < numberOfLines; i++)
{
    System.IO.StreamWriter file = new System.IO.StreamWriter(logPath);
    runBrowserThread(i);
}

logPath变量引用目录的路径,而不是文件。 要创建文件,您可以执行以下操作......

string logPath = @"c:\Logs";
string logFile = Path.Combine(logPath, DateTime.UtcNow.ToString("HH-mm-ss") + ".log");

// Directory.CreateDirectory(logPath);

using (TextWriter writer = new StreamWriter(logFile))
{
    writer.WriteLine("testing random log");
}

// Process.Start(logFile);