【问题标题】:C# Filestream file lockingC# Filestream 文件锁定
【发布时间】:2020-10-16 13:43:02
【问题描述】:

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

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);



            }
        }
}

【问题讨论】:

  • 代码缺少using 语句,这是确保流关闭所必需的。

标签: c# filestream


【解决方案1】:

假设您使用的是Devexpress.RichEditConrol,所以这不会锁定文件。

RichEdit 控件是可以在应用程序中使用的控件, 所以文件锁定应该在应用程序级别实现,而不是在 控制一。

看看这里的讨论: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();
        }
    }
}

【讨论】:

    猜你喜欢
    • 2011-08-27
    • 1970-01-01
    • 1970-01-01
    • 2012-04-30
    • 2021-08-14
    • 2018-04-19
    • 2014-02-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多