18
如果在创建文件时出现问题,我一直在写入临时文件,然后移动到目的地。喜欢的东西:File.Move不从目标目录继承权限?
var destination = @"C:\foo\bar.txt";
var tempFile = Path.GetTempFileName();
using (var stream = File.OpenWrite(tempFile))
{
// write to file here here
}
string backupFile = null;
try
{
var dir = Path.GetDirectoryName(destination);
if (!Directory.Exists(dir))
{
Directory.CreateDirectory(dir);
Util.SetPermissions(dir);
}
if (File.Exists(destination))
{
backupFile = Path.Combine(Path.GetTempPath(), new Guid().ToString());
File.Move(destination, backupFile);
}
File.Move(tempFile, destination);
if (backupFile != null)
{
File.Delete(backupFile);
}
}
catch(IOException)
{
if(backupFile != null && !File.Exists(destination) && File.Exists(backupFile))
{
File.Move(backupFile, destination);
}
}
的问题是,新的“跳回到bar.txt”在这种情况下不继承从“C:\富”权限的目录。然而,如果我直接在“C:\ foo”中通过资源管理器/记事本等创建文件,则没有问题,所以我相信在“C:\ foo”上正确设置了权限。
更新
发现Inherited permissions are not automatically updated when you move folders,也许它适用于文件以及。现在正在寻找一种强制更新文件权限的方法。这样做是否有更好的方法?
一旦文件已被移动,您是否必须执行此操作?在这种情况下,它不再是原子性的 - 在权限到位之前,有人可能尝试读取该文件的风险 – Neil 2012-04-24 12:03:19
@尼尔是的,这是在移动之后,是的,它会使它不再是原子。 – 2012-04-25 13:27:16
@JosephKingry。谢谢,这帮了我。但是,我也想移除任何明确的权限作为移动的结果。再多几行代码。 http://stackoverflow.com/a/12821819/486660 – Jim 2012-10-10 18:57:10