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:\foo”目录的权限。然而,如果我直接在“C:\foo”中通过资源管理器/记事本等创建文件,则没有问题,所以我相信“C:\foo”上的权限设置正确。
发现更新
移动文件夹时继承的权限不会自动更新,也许它也适用于文件。现在正在寻找一种强制更新文件权限的方法。总体上有更好的方法吗?
In case something goes wrong in creating a file, I've been writing to a temporary file and then moving to the destination. Something like:
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);
}
}
The problem is that the new "bar.txt" in this case does not inherit permissions from the "C:\foo" directory. Yet if I create a file via explorer/notepad etc directly in the "C:\foo" there's no issues, so I believe the permissions are correctly set on "C:\foo".
Update
Found Inherited permissions are not automatically updated when you move folders, maybe it applies to files as well. Now looking for a way to force an update of file permissions. Is there a better way overall of doing this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
发现我需要的是这样的:
这会将文件权限重置为继承。
Found what I needed was this:
This resets the file permissions to inherit.