4

I am trying to create a log file in my program:

if (!File.Exists("c://log.txt"))
{
    File.Create("c://log.txt");
}

I have received this error:

Access to the path 'c:\log.txt' is denied

How can i get access to c ?

Thanks.

user2153436
  • 81
  • 1
  • 1
  • 7
  • 1
    Which operating system? Windows 7 or windows 8? And what user starts the program a normal one or one with administrator rights? – Thomas Sep 24 '14 at 12:46
  • 3
    If the call to `Exists` or `Create` failing. It looks like permissions are coming into play. – Ken Brittain Sep 24 '14 at 12:48
  • I am using Windows 8. The current user have administrator rights. – user2153436 Sep 24 '14 at 12:49
  • How can i ask the user for administrator rights? – user2153436 Sep 24 '14 at 12:50
  • Some paths are not writable in Windows for normal users. The only path that always is writable, even as a guest, is the user directory, and of course %temp%. With every other path you have to check whether you have permissions - either explicitly, or by try{create}catch{createInUserDirectory}. What I wouldn't even think of is force the user to give additional permissions just because you want to write a logfile... – Alexander Sep 24 '14 at 12:51
  • 1
    at all, the `C` drive and this main path, is not suitable for writing, choice another path (if you can) – Mehdi Khademloo Sep 24 '14 at 12:51
  • 1
    Do you also run your VisualStudio as admin? You have to explicitly run it as admin to get admin-rights, no matter, if your current user is admin or not. – MakePeaceGreatAgain Sep 24 '14 at 12:54
  • @HimBromBeere - exactly - RUN AS ADMINISTRATOR!!! – T.S. Sep 24 '14 at 14:33

1 Answers1

6

I think you have to force .NET to run this programm as administrator:

How do I force my .NET application to run as administrator?

But you should write your log file any where else then "C:\", you can use a temp directory like this http://msdn.microsoft.com/de-de/library/system.io.path.gettemppath(v=vs.110).aspx or you use something like "C:\temp"

If you like to write your log file into the directory of the executing assembly use this to get the directory:

System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location)
Community
  • 1
  • 1
joh.scheuer
  • 566
  • 3
  • 11
  • 4
    Q: My door won't open when I push the handle, help? A: Use a crowbar to break in. -- This might or might not be a good solution, depending on context (to keep the analogy, great idea if the house is on fire). – decPL Sep 24 '14 at 12:55
  • That's true. Therefore i said that he should not write a log file to "C:\". – joh.scheuer Sep 24 '14 at 13:00
  • It did run when used as an administrator – Rajat Mar 23 '17 at 10:37