我希望写入受保护的文本文件注意此内容很重要。我可以写入文件以保护它吗?我将使用加密,但不希望任何人读取文件的内容。我试过使用 File.WriteText?但问题是文件被写入然后未使用,因此任何人都可以读取内容。
保护例如。像 SAM 文件
在 Microsoft Dotnet 框架中, C# 中提供的TextFile 属性将使您能够保持文件加密和只读。可以使用FileIOPermissionAccesss完成写保护 如果当前用户是管理员,那么他将能够为特定的文件提供保护和删除权限。下面是添加权限的示例代码。
var permissionSet = new PermissionSet(PermissionState.None);
var writePermission = new FileIOPermission(FileIOPermissionAccess.Write, filename);
permissionSet.AddPermission(writePermission);
if (permissionSet.IsSubsetOf(AppDomain.CurrentDomain.PermissionSet))
{
using (FileStream fstream = new FileStream(filename, FileMode.Create))
using (TextWriter writer = new StreamWriter(fstream))
{
// try catch block for write permissions
writer.WriteLine("sometext");
}
}
else
{
//perform some recovery action here
}
I too faced similar problem, instead in my case the problem was the data in my file should be visible to anyone even to the admin user, and for every time the application runs the previous data should be replaced by the new one.
Here's my code
string pathfile = @"C:\Users\Public\Documents\Filepath.txt";
if (File.Exists(pathfile))
{
File.Delete(pathfile);
}
if (!File.Exists(pathfile))
{
using (FileStream fs = File.Create(pathfile))
{
Byte[] info = new UTF8Encoding(true).GetBytes("Your Text Here");
fs.Write(info, 0, info.Length);
FileSecurity fsec = File.GetAccessControl(pathfile);
fsec.AddAccessRule(new FileSystemAccessRule("Everyone",
FileSystemRights.FullControl, AccessControlType.Deny));
File.SetAccessControl(pathfile, fsec);
}
}