Always Getting Access Denied Error When I Write A File Inside Created Folder

5.8k Views Asked by At

I'm using windows (testing in 7 and 10)

And program creating folder first. After that, i want to write a file inside created folder. But always getting access denied error. I tried every directory in operating system. C: , programfiles, documents and project folder. Always i get that error message. Every Code is below, thank you.

app.manifest

<requestedExecutionLevel level="requireAdministrator" uiAccess="false" />

Create Folder Button Method

private void button2_Click(object sender, EventArgs e)
{
    string path = "FullControl";    // Or C:\\FullControl  > Doesn't matter same error
    bool exist = System.IO.Directory.Exists(path);
    if (!exist)
    {
        Directory.CreateDirectory(path);
    }
    var fInfo = new DirectoryInfo(path);
    var sid = new SecurityIdentifier(WellKnownSidType.WorldSid, null);
    var Security = fInfo.GetAccessControl(AccessControlSections.Access);
    Security.AddAccessRule(new FileSystemAccessRule(sid, FileSystemRights.FullControl, InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit, PropagationFlags.None, AccessControlType.Allow));

}

Remove Folder ReadOnly

    private void button3_Click(object sender, EventArgs e)
    {
        string path = "FullControl";
        var fInfo = new DirectoryInfo(path);
        FileAttributes f = fInfo.Attributes;
        DecipherAttributes(path, f);  //I dont now is it necessary ?
    }

Create and Write File Button Method

    private void button4_Click(object sender, EventArgs e)
    {
        string path = "FullControl";
        string filePath = path + "FullControl\\Example.html";

        if (!File.Exists(path))
        {
            try
            {
                StreamWriter tw = new StreamWriter(File.Open(path, FileMode.OpenOrCreate, FileAccess.Write), Encoding.UTF8);
                tw.WriteLine("The very first line!");
                tw.Close();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
        else if (File.Exists(path))
        {
            StreamWriter tw = new StreamWriter(File.Open(path, FileMode.Open, FileAccess.ReadWrite), Encoding.UTF8);
            tw.WriteLine("The next line!");
            tw.Close();
        }
    }

Folder Attribute Method

    public static void DecipherAttributes(String path ,FileAttributes f)
    {
        // To set use File.SetAttributes

        File.SetAttributes(path, FileAttributes.ReadOnly);

        if ((f & FileAttributes.ReadOnly) == FileAttributes.ReadOnly)
            Console.WriteLine("ReadOnly");

        // To remove readonly use "-="
        f -= FileAttributes.ReadOnly;

        if ((f & FileAttributes.ReadOnly) == FileAttributes.ReadOnly)
            Console.WriteLine("ReadOnly");
        else
            Console.WriteLine("Not ReadOnly");
    }
1

There are 1 best solutions below

1
On BEST ANSWER

I change the code like this, and it's worked. I think the Path.Combine() is the solution. Thanks all comments.

String FolderPath = Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData);
FolderPath = Path.Combine(FolderPath,"TestFolder");
String file = Path.Combine(FolderPath,"test.html");

if (!File.Exists(file))
  {
    try
      {
          StreamWriter tw = new StreamWriter(File.Open(file, FileMode.OpenOrCreate, FileAccess.Write), Encoding.UTF8);
          tw.WriteLine("The very first line!");
          tw.Close();
          MessageBox.Show("File Created");
      }
      catch (Exception ex)
      {
          MessageBox.Show(ex.Message);
      }
   }