0

我正在使用 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);
    }
}

正如我之前所说,该应用程序在运行期间工作正常,但是当我关闭它时,锁定的文件将被解锁。

如果有人对如何做到这一点有任何想法,我将不胜感激。

4

3 回答 3

5

A Lock on a FileStream just means that your process has exclusive access to the file while it's active; it has nothing to do with password protecting a file.

It sounds like what you want is to encrypt a file with a password. The file class provides Encrypt/Decrypt based on the current user, or, if you want it based on your own custom password there's a sample of using some of the classes in the System.Security.Cryptography namespace to encrypt a file with a password here (instead of hard coding you would take it as input presumably) http://www.codeproject.com/Articles/26085/File-Encryption-and-Decryption-in-C

Keep in mind, doing security right is hard.

于 2012-10-12T23:50:07.447 回答
2

您正在使用该FileStream.Lock()方法锁定特定文件,以便只有运行该文件的进程FileStream才能使用它。

http://msdn.microsoft.com/en-us/library/system.io.filestream.lock.aspx

这是一种旨在防止其他进程写入您正在读取/写入的文件的机制,您可以在 Microsoft Excel 等应用程序中看到此方法。

当您关闭应用程序时,该进程不再运行,并且文件上的锁定被解除。

如果您的目标是阻止其他应用程序读取该文件,那么您有一些有限的选择:

  1. 加密文件。这意味着应用程序无法在没有解密密钥的情况下从文件中读取可用信息,但应用程序有可能打开和更改加密文件。
  2. 将文件保存到只读媒体(如 CD/DVD)或可移动存储中,然后拔下插头并随身携带。

如果您想阻止其他应用程序修改文件,您可以查看 Windows 提供的 ReadOnly 标志:http: //msdn.microsoft.com/en-us/library/system.io.fileinfo.isreadonly.aspx

请注意,这些仍然是不安全的,因为可以忽略只读标志。

您需要考虑的是您为什么要限制对文件的访问的推理 - 这将有助于确定限制访问的最佳策略。

于 2012-10-12T23:56:23.173 回答
0

If all you need to do is make sure nothing else can read or modify the file while you've got your application locking it, the below should do the job.

If you need anything more, look into proper file encryption techniques.

Note that if you close the application the lock will no longer be in effect.

    System.IO.FileStream fileStream;

    private void LockFile(string FilePath)
    {
        fileStream = System.IO.File.Open(FilePath, System.IO.FileMode.Open, System.IO.FileAccess.ReadWrite, System.IO.FileShare.None);
        //using System.IO.FileShare.None in the above line should be sufficient, but just to go the extra mile...
        fileStream.Lock(0, fileStream.Length);
    }

    private void UnlockFile()
    {
        if (fileStream != null)
        {
            try { fileStream.Unlock(0, fileStream.Length); }
            finally { fileStream.Dispose(); }
        }
    }
于 2012-10-12T23:49:32.750 回答