Ошибка всегда получения доступа при записи файла в созданную папку

Я использую Windows (тестирование в 7 и 10)

И программа создает папку в первую очередь. После этого я хочу написать файл внутри созданной папки. Но всегда получая доступ отказано в ошибке. Я перепробовал каждый каталог в операционной системе. C:, программные файлы, документы и папка проекта. Всегда получаю это сообщение об ошибке. Каждый код ниже, спасибо.

app.manifest

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

Метод создания папки

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

}

Удалить папку только для чтения

    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 ?
    }

Метод создания и записи файла

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

Метод атрибута папки

    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 ответ

Решение

Я изменяю код следующим образом, и он работает. Я думаю, что Path.Combine() является решением. Спасибо за все комментарии.

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);
      }
   }
Другие вопросы по тегам