Вопрос

I am trying to write text to a file in my visual studio project. If the file does not exist I want to create it in the project.

When I try to implement the method that writes the text to the new file, the following error occurs:

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

Seeing as though the root path will be different on each computer where the program is installed, how do I ensure this method can/will create a new text file in the user's project? (without knowing the root URL).

The method, that when called, should write text to a file.

    /// <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();
    }

Any help would be hugely appreciated!

Thank you in advance

Это было полезно?

Решение

If this is a Web Project (ASP.NET) then you should write your log file in the standard folders provided they exists under your root site folder. By default you are unable to write outside the root folder for security reasons

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);
    }
}

The folder APP_DATA under your root folder is used when read/write permissions are required by your code (database files, log files and other data files).
Notice also that a StreamWriter should be enclosed in the using statement to ensure proper closing in the eventuality of an exception or other write problems.

Другие советы

I had the same problem, suddenly, though it was working fine. After some checking and trying, it turned out that the antivirus software was the cause of this problem: access denied to file. I stopped the antivirus, temporarily, and no more access denied no matter what is the location of the file.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top