繁体   English   中英

C#未经授权的访问异常

[英]C# Unauthorized Access Exception

尝试打开文件时出现未授权访问异常

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

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

该代码试图像写入文件一样写入目录。

尝试使用引用目录的文件路径创建文件时,系统将显示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);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM