我正在使用 Windows(在 7 和 10 中测试)
和程序首先创建文件夹。之后,我想在创建的文件夹中写一个文件。但总是收到拒绝访问错误。我尝试了操作系统中的每个目录。C:、programfiles、文档和项目文件夹。我总是收到该错误消息。每个代码都在下面,谢谢。
应用程序清单
<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");
}