从删除,移动或重命名文件防止用户 [英] Prevent a user from deleting, moving or renaming a file

查看:380
本文介绍了从删除,移动或重命名文件防止用户的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我所试图做的是,而我的程序正在使用的文件,我想保持从重命名,删除或移动文件的用户(嗯......一招是删除,并在不同的位置创建根据到Windows FileSystemWatcher的,但我离题)。

What I am trying to do is while my program is using a file, I want to keep the user from renaming, deleting, or moving the file (well... a move is a delete and a create at a different location according to Windows FileSystemWatcher, but I digress).

有人建议我用的 FileStream.Lock 或使用的互斥。然而,FileStream.Lock似乎只是为了防止文件被修改的而我试图让的。另外,我作为如果互斥锁可以锁定文件非常不确定,但我还是在.NET 4.0图书馆阅读它。

It has been suggested that I use FileStream.Lock or use a Mutex. However, FileStream.Lock seems only to prevent the file from being modified which I am trying to allow. Also, I am very unsure as to if a mutex can lock a file, although I am still reading on it with in the .Net 4.0 library.

有没有人有任何在使用任何一个和建议,如果有一个基于代码的解决这个问题?

Does anyone have any advice on utilizing either one and if there is a code based solution to this problem?

推荐答案

当您打开该文件时,可以指定共享模式。

When you are opening the file, you can specify the sharing mode.

打开文件, FileAccess.Read 使您能够读取文件的能力,同时 FileShare.ReadWrite 允许,该文件以继续进行编辑,但不能删除或移动

Opening the file with FileAccess.Read gives you the ability to read the file, while FileShare.ReadWrite allows the file to continue to be edited, but not deleted or moved.

var fs = File.Open(@"C:\temp\file.txt", FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
MessageBox.Show("File Locked");  // While the messagebox is up, try to open or delete the file.
// Do your work here
fs.Close();

这篇关于从删除,移动或重命名文件防止用户的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆