简体   繁体   中英

C# Filestream file locking

I have a problem with File Locking. I don't know why but I can delete, the used and opened Document with my application, Here is the Code. Can someone help me out?

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



            }
        }
}

Assuming you are using Devexpress.RichEditConrol , so this does not lock the file.

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.

Take a look at discussion here: https://supportcenter.devexpress.com/ticket/details/t418100/opening-same-file-by-multiple-instances-of-richeditcontrol

What you can do it that locking this file manually:

From 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();
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM