C# Filestream 文件锁定

C# Filestream file locking

我的文件锁定有问题。我不知道为什么,但我可以用我的应用程序删除、使用和打开的文档,这是代码。有人可以帮我吗?

public Form1()
{

        InitializeComponent();
Document location path  
        var args = System.Environment.GetCommandLineArgs();

argPath
         var argPath = args.Skip(1).FirstOrDefault();

        if (!string.IsNullOrEmpty(argPath))
        {

           var fullPath = Path.GetFullPath(argPath);


            if (!string.IsNullOrEmpty(fullPath))
            {

                FileStream Fs2 = new FileStream(fullPath, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.None);



            }
        }
}

假设您正在使用 Devexpress.RichEditConrol,因此这不会锁定文件。

The RichEdit control is a control that can be used in an application, so file locking should be implemented at the application level, not at the control one.

看看这里的讨论:https://supportcenter.devexpress.com/ticket/details/t418100/opening-same-file-by-multiple-instances-of-richeditcontrol

手动锁定此文件的方法:

来自How to manually Lock a file for other applications

 public class FileLock : IDisposable
 {
    private FileStream _lock;
    public FileLock(string path)
    {
        if (File.Exists(path))
        {
            _lock = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.None);
            IsLocked = true;
        }            
    }

    public bool IsLocked { get; set; }

    public void Dispose()
    {
        if (_lock != null)
        {
            _lock.Dispose();
        }
    }
}