我正在使用windows(在7和10中测试)
程序先创建文件夹。在那之后,我想在创建的文件夹里写一个文件。但总是得到访问拒绝错误。我试了操作系统里的所有目录。C: programfiles、documents和project文件夹。我总是得到那个错误信息。每个代码都在下面,谢谢。
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));
}
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 ?
}
创建和写入文件按钮方法
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");
}
我像这样修改代码,它工作了。我认为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);
}
}