mod*_*irl 9 c# file-permissions file streamwriter
我正在使用C#StreamWritier
类.问题:
我正在创建这样的文件:
private void button1_Click(object sender, EventArgs e)
{
SaveFileDialog save = new SaveFileDialog();
save.FileName = textBox1.Text;
save.Filter = "Text File | *.rtf";
if (save.ShowDialog() == DialogResult.OK)
{
StreamWriter writer = new StreamWriter(save.OpenFile());
writer.WriteLine(textBox2.Text);
}
writer.Dispose();
writer.Close();
}
Run Code Online (Sandbox Code Playgroud)
Agh*_*oub 11
您好,您可以尝试使用此方法
1
public static void SetFileReadAccess(string FileName, bool SetReadOnly)
{
FileInfo fInfo = new FileInfo(FileName);
// Set the IsReadOnly property.
fInfo.IsReadOnly = SetReadOnly;
}
Run Code Online (Sandbox Code Playgroud)
2
File.SetAttributes(yourFilePath, FileAttributes.Hidden);
Run Code Online (Sandbox Code Playgroud)
......
您可以使用设置ReadOnly属性File.SetAttributes
.
例:
File.SetAttributes(textBox1.Text, FileAttributes.ReadOnly);
Run Code Online (Sandbox Code Playgroud)
请注意,这仅设置readonly标志,它不会修改NTFS访问控制列表(这意味着每个熟练的用户都可以删除只读属性).另请注意,这会重置文件的所有其他属性,这在您的情况下应该不是问题,因为您无论如何都要创建新文件.如果需要保留现有属性,File.GetAttributes
请先使用并将现有标志与新标志合并(请参阅链接的MSDN页面上的示例).
如果您需要保护文件免受恶意写入攻击,您必须了解NTFS安全性(谷歌为"NTFS安全"提供大量资源).一旦你理解了这一点,下面的问题将告诉你如何在C#中修改它们:
将此用于只读文件:
FileAttributes yourFile = File.GetAttributes(yourFilePath);
File.SetAttributes(yourFilePath, FileAttributes.ReadOnly);
Run Code Online (Sandbox Code Playgroud)
其中“ yourFilePath”是字符串。
对于隐藏文件:
FileAttributes yourFile = File.GetAttributes(yourFilePath);
File.SetAttributes(yourFilePath, FileAttributes.Hidden);
Run Code Online (Sandbox Code Playgroud)
对于普通文件(非只读或隐藏文件):
FileAttributes yourFile = File.GetAttributes(yourFilePath);
File.SetAttributes(yourFilePath, FileAttributes.Normal);
Run Code Online (Sandbox Code Playgroud)
我知道您没有要求设置普通文件,但我认为了解这一点很有用。
归档时间: |
|
查看次数: |
13509 次 |
最近记录: |