简体   繁体   English

UnauthorizedAccessException StreamWriter

[英]UnauthorizedAccessException StreamWriter

I have the following code: 我有以下代码:

public WriteToFile(string path, List<string> text)
{
    File.Delete(path);
    using (TextWriter writer = new StreamWriter(path, true))
    {
        foreach(string t in text)
        {
            writer.WriteLine(text);
        }
    }
}

Most of the time it works fine, the file is deleted and then created again with the text inside. 在大多数情况下,它可以正常工作,该文件将被删除,然后使用内部文本再次创建。 However every so often the using statement throws an UnauthorizedAccessException . 但是, using语句经常会抛出UnauthorizedAccessException Any idea why? 知道为什么吗? I have admin rights and the program is run as admin. 我具有管理员权限,该程序以管理员身份运行。

This is normal, it became undiagnosable because you used File.Delete(). 这是正常现象,因为您使用了File.Delete(),因此无法诊断。 Which is unnecessary, just use the StreamWriter(string) constructor. 这是不必要的,只需使用StreamWriter(string)构造函数。

This goes wrong because deleting a file doesn't provide a guarantee that the file will actually be deleted. 这是错误的,因为删除文件并不能保证该文件实际上将被删除。 It may be opened by another process. 可以通过另一个进程打开它。 Which has opened the file with delete sharing, programs like virus scanners and file indexers commonly do this. 通过删除共享打开文件的程序通常使用病毒扫描程序和文件索引器之类的程序。 Which makes the Delete() call succeed but the file doesn't disappear until all handles on the file are closed. 这使得Delete()调用成功,但是直到关闭文件上的所有句柄后文件才消失。 You got the UnauthorizedAccessException exception because the file didn't get deleted yet. 您收到UnauthorizedAccessException异常,因为文件尚未删除。

Get ahead by removing the File.Delete() call. 通过删除File.Delete()调用来取得成功。 You still need to assume that the StreamReader() constructor can fail. 您仍然需要假设StreamReader()构造函数可能会失败。 Less often, it is bound to happen sooner or later. 它很少会迟早发生。 You'll get a better exception message. 您会收到更好的异常消息。 Such are the vagaries of a multi-tasking operating system. 这就是多任务操作系统的多变之处。

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

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