Kiwimoisi
Kiwimoisi

Reputation: 4182

Write a log file

I have a recent problem . I can upload file in my intetpub/wwwrooot/folder

But I can't write a log file in this same folder ...

I have all the permissions for the network service. Everything is on my server.

DirectoryInfo di = new DirectoryInfo(~/);

// Get a reference to each file in that directory.
FileInfo[] fiArr = di.GetFiles();


string strLogText = di;

// Create a writer and open the file:
StreamWriter log;

if (!System.IO.File.Exists("C:\\inetpub\\wwwroot\\logfile.txt"))
{
    log = new StreamWriter("C:\\inetpub\\wwwroot\\logfile.txt");
}
else
{
    log = System.IO.File.AppendText("C:\\inetpub\\wwwroot\\logfile.txt");
}

// Write to the file:
log.WriteLine(DateTime.Now);
log.WriteLine(strLogText);
log.WriteLine();

// Close the stream:
log.Close();

The error is the access is denied !

It works locally , but on my server it doesnt. On the folder Inetpub , I just need to allow writting for Network service ? That is strange because I can upload file and writting is already enable

Upvotes: 1

Views: 3148

Answers (3)

sfuqua
sfuqua

Reputation: 5853

On the server, is the web app running under an Application Pool that has alternate credentials, other than the normal network service account? If you haven't done so already, try turning on Auditing to see what user is trying to access the file.

Upvotes: 0

Davide Piras
Davide Piras

Reputation: 44605

Emged in case of exceptions your code does not close the streams on the log file and this is surely not good.

You should use a using statement around the streams so in any case streams are closed and disposed also in case of exceptions.

As Chris has suggested I would absolutely opt for a logging Framework and I would also avoid writing in that wwwroot folder.

ELMAH or NLog or Log4Net are good and easy alternatives far better than any custom logging lie you are doing right now and the big advantage of these technologies/libraries is that you can change the behaviour at runtime simply by editing the configuration file, no need to rebuild or redeploy anything...

my favourite is actually Log4Net, check these ones for a simple example on how to use it:

http://logging.apache.org/log4net/release/manual/configuration.html

Log4Net in App object?

Upvotes: 2

ChrisLively
ChrisLively

Reputation: 88064

Depending on the version of your server (windows 2008 and above), that directory has additional protection against writes.

I'd highly recommend you look into ELMAH to do your logging. It gives you a number of options including in memory or database backed and collects a LOT of additional data you might want.

Further, opening up various physical directory locations for write access is a HUGE security no-no.

Upvotes: 0

Related Questions