c#怎麼解決System.UnauthorizedAccessException異常

https://blog.csdn.net/qq_38061677/article/details/81157116spa

代碼:.net

using System;
namespace Project2048
{
class Program
{
static void Main(string[] args)
{
FileInfo fileInfo1 = new FileInfo("555.txt");//該文件是存在的
string str = "hello";
File.AppendAllText(fileInfo1.DirectoryName, str);
Console.ReadKey();
}blog

}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
System.UnauthorizedAccessException解析
在VS默認的解釋是: path 指定了一個只讀文件。- 或 -在當前平臺上不支持此操做。- 或 -path 指定了一個目錄。- 或 -調用方沒有所要求的權限。
疑惑string

FIleInfo類實例化,默認的的只讀屬性是false,也就是說。能夠進行讀寫的,怎麼會出System.UnauthorizedAccessException」錯誤?io

通過仔細尋找發現問題是fileInfo1.DirectoryName,這個方法是獲取文件的目錄,並非到當前文件。使用fileInfo.Name就能夠了
代碼:class

using System;
namespace Project2048
{
class Program
{
static void Main(string[] args)
{
FileInfo fileInfo1 = new FileInfo("555.txt");//該文件是存在的
string str = "hello";
File.AppendAllText(fileInfo1.Name, str);
Console.ReadKey();
}file

}
}
---------------------
做者:小小liang
來源:CSDN
原文:https://blog.csdn.net/qq_38061677/article/details/81157116
版權聲明:本文爲博主原創文章,轉載請附上博文連接!權限

相關文章
相關標籤/搜索