[英]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.