File.CreateText - Access Denied

3.9k Views Asked by At

I recently spent a while trying to figure out what permissions were needed to get this statement to work:

if (!File.Exists(path)) 
{
    // Create a file to write to. 
    using (StreamWriter sw = File.CreateText(path)) 
    {
        sw.WriteLine("Hello");
        sw.WriteLine("And");
        sw.WriteLine("Welcome");
    }   
}

I eventually have "Special Permissions" to "Everyone" which should have solved the problem. Sadly it didn't, it may actually be a bug?

The following works:

if (!File.Exists(_logFilePath))
{
    using (var fs = File.Create(_logFilePath))
    {
        using (var sw = new StreamWriter(fs))
        {
             sw.WriteLine("Hello");
             sw.WriteLine("And");
             sw.WriteLine("Welcome");
        }
    }
}

Theoretically identical (I think), but I couldn't get the first to work.

1

There are 1 best solutions below

0
On

I think the path variable is wrong. Make sure you've also entered the file name in the path.