【发布时间】:2012-10-12 23:36:37
【问题描述】:
我正在 VS2010 上使用 C# 开发文件锁定器/解锁器应用程序。 我想要的是使用我的应用程序使用密码锁定文件,然后随时解锁。
事实上,我使用下面的代码来锁定文件,但文件只是在应用程序仍在运行时才被锁定;当我关闭应用程序时,文件被解锁。
using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Configuration;
using System.Windows.Forms;
namespace LockFile
{
public enum LockStatus
{
Unlocked,
Locked
}
public class LockFilePresenter
{
private ILockFileView view;
private string file2Lock = string.Empty;
private FileStream fileLockStream = null;
public LockFilePresenter(ILockFileView view)
{
this.view = view;
}
internal void LockFile()
{
if (string.IsNullOrEmpty(file2Lock) || !File.Exists(file2Lock))
{
view.ShowMessage("Please select a path to lock.");
return;
}
if (fileLockStream != null)
{
view.ShowMessage("The path is already locked.");
return;
}
try
{
fileLockStream = File.Open(file2Lock, FileMode.Open);
fileLockStream.Lock(0, fileLockStream.Length);
view.SetStatus(LockStatus.Locked);
}
catch (Exception ex)
{
fileLockStream = null;
view.SetStatus(LockStatus.Unlocked);
view.ShowMessage(string.Format("An error occurred locking the path.\r\n\r\n{0}", ex.Message));
}
}
internal void UnlockFile()
{
if (fileLockStream == null)
{
view.ShowMessage("No path is currently locked.");
return;
}
try
{
using (fileLockStream)
fileLockStream.Unlock(0, fileLockStream.Length);
}
catch (Exception ex)
{
view.ShowMessage(string.Format("An error occurred unlocking the path.\r\n\r\n{0}", ex.Message));
}
finally
{
fileLockStream = null;
}
view.SetStatus(LockStatus.Unlocked);
}
internal void SetFile(string path)
{
if (ValidateFile(path))
{
if (fileLockStream != null)
UnlockFile();
view.SetStatus(LockStatus.Unlocked);
file2Lock = path;
view.SetFile(path);
}
}
internal bool ValidateFile(string path)
{
bool exists = File.Exists(path);
if (!exists)
view.ShowMessage("File does not exist.");
return exists;
}
}
}
和
using System;
using System.Collections.Generic;
using System.Text;
namespace LockFile
{
public interface ILockFileView
{
void ShowMessage(string p);
void SetStatus(LockStatus lockStatus);
void SetFile(string path);
}
}
正如我之前所说,应用程序在运行期间工作正常,但是当我关闭它时,锁定的文件将被解锁。
如果有人知道如何做,我将不胜感激。
【问题讨论】:
-
Locking这里是特定于线程的,因此当您关闭应用程序(并终止线程)时,其他程序可以访问该文件。我想你可能想研究密码保护/加密。 -
不知何故,我确实认为您正在滥用锁定系统做一些不应该做的事情;这与访问权限无关,而是确保应用程序不会获得无效输入或弄乱文件。
-
@owlstead 那么你有什么建议呢? ..有什么建议吗?谢谢
-
除了加密文件之外,实现此目的的唯一方法是让应用程序保持活动状态。您可以通过在后台运行应用程序实例来实现这一点,例如作为服务,但我不建议这样做。
-
哈桑,你已经接受了我会选择的答案。有时你不需要加密,最终它是关于访问看起来的文件,在这种情况下,访问权限也会浮现在脑海中。
标签: c# encryption filestream file-locking