问题描述
最近复习c#文件操作,在用
File.AppendAllText((string path, string contents)
方法往一个文件写一段字符串的时候出现了“System.UnauthorizedAccessException”类型的未经处理的异常 。疑难答问提示是:如果您要访问某个文件,请确保该文件不是自读。
代码:
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();
}
}
}
System.UnauthorizedAccessException解析
在VS默认的解释是: path 指定了一个只读文件。- 或 -在当前平台上不支持此操作。- 或 -path 指定了一个目录。- 或 -调用方没有所要求的权限。
疑惑
FIleInfo类实例化,默认的的只读属性是false,也就是说。可以进行读写的,怎么会出
System.UnauthorizedAccessException”
错误?
经过仔细寻找发现问题是fileInfo1.DirectoryName
,这个方法是获取文件的目录,并不是到当前文件。使用fileInfo.Name
就可以了
代码:
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();
}
}
}