gpt4 book ai didi

c# - 难以将文本写入 C# 中的新文件,根路径错误,访问被拒绝

转载 作者:太空宇宙 更新时间:2023-11-03 10:45:21 26 4
gpt4 key购买 nike

我正在尝试将文本写入我的 visual studio 项目中的文件。如果该文件不存在,我想在项目中创建它。

当我尝试实现将文本写入新文件的方法时,出现以下错误:

Exception Details: System.UnauthorizedAccessException: Access to the path 'C:\Windows\SysWOW64\inetsrv\ErrorLog' is denied.

好像安装程序的每台计算机上的根路径都不同,我如何确保此方法可以/将在用户项目中创建一个新的文本文件? (不知道根 URL)。

调用时应将文本写入文件的方法。

    /// <summary>
/// Logs a message to a file.
/// </summary>
/// <param name="msg">
/// The message.
/// </param>
public void LogMessageToFile(string message)
{
TextWriter tw = new StreamWriter("ErrorLog");
tw.WriteLine(message);
tw.Close();
}

如有任何帮助,我们将不胜感激!

提前致谢

最佳答案

如果这是一个 Web 项目 (ASP.NET),那么您应该将您的日志文件写入标准文件夹中,前提是它们存在于您的根站点文件夹下。默认情况下,出于安全原因,您无法在根文件夹之外写入

public void LogMessageToFile(string message)
{
// Get the physical path corresponding to the root folder of your site plus APP_DATA
string appData = Server.MapPath("~/APP_DATA");

// Create the log file name
string logFile = Path.Combine(appData, "ErrorLog.txt");

// Append to the log file and close/dispose the stream
using(StreamWriter aw = new StreamWriter(logFile, true))
{
sw.WriteLine(message);
}
}

当您的代码(数据库文件、日志文件和其他数据文件)需要读/写权限时,将使用根文件夹下的文件夹 APP_DATA。
另请注意,应将 StreamWriter 包含在 using 语句中,以确保在发生异常或其他写入问题时正确关闭。

关于c# - 难以将文本写入 C# 中的新文件,根路径错误,访问被拒绝,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23654670/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com