无法在文件中写入 AppedText

Unable to write AppedText in file

我需要创建一个文件,并且需要在文件中写入每个异常。我正在使用波纹管代码来做到这一点。

File.Create(filePath);
File.AppendText("Exception Detail Start-------------------------------------------");
File.AppendText("Stack Trace :" + ex.StackTrace );
File.AppendText("Error :" + ex.Message );
File.AppendText("Exception Detail End-------------------------------------------");

但我收到以下错误:

Additional information: Access to the path 'C:\Program Files (x86)\IIS Express\Exception Detail Start-------------------------------------------' is denied`

您的 C\program 文件 (x86) 路径通常需要管理权限才能写入文件。尝试以管理员身份启动您的应用程序。 (或者以管理员身份 visual studio 和 运行 你的项目启动)

如果在 运行 作为管理员时成功写入文件,可以考虑选择一个不需要管理权限的文件夹,或者将权限添加到为您的程序选择的文件夹。

File.AppendText 取一个文件路径和 returns 一个 StreamWriter。因此,在您的情况下,您将异常消息作为文件路径传递,因此找不到文件(它正在查找当前目录中名为 "Exception Detail Start-------------------------------------------" 的文件)。

在您的情况下,您可能希望使用 File.AppendAllText

Opens a file, appends the specified string to the file, and then closes the file. If the file does not exist, this method creates a file, writes the specified string to the file, then closes the file.

File.AppendAllLines.

Appends lines to a file, and then closes the file. If the specified file does not exist, this method creates a file, writes the specified lines to the file, and then closes the file.

示例:

File.AppendAllLines(filePath, new string[] { 
    "Exception Detail Start-------------------------------------------",
    "Stack Trace :" + ex.StackTrace, 
    "Error :" + ex.Message, 
    "Exception Detail End-------------------------------------------" 
});

您没有写入您创建的文件。

FileStream writer = File.Create(filePath);
writer.AppendText("Exception Detail Start-------------------------------------------");
writer.AppendText("Stack Trace :" + ex.StackTrace );
writer.AppendText("Error :" + ex.Message );
writer.AppendText("Exception Detail End-------------------------------------------");

这应该有效。