17

please tell me how to lock file in c#

Thanks

MusiGenesis
  • 74,184
  • 40
  • 190
  • 334
Naruto
  • 9,476
  • 37
  • 118
  • 201
  • This could result in dozens of different answers, which would all be valid. Please add more specifics. (Btw, just opining the file could already block quite a few others from accessing it.) – Wim ten Brink Sep 16 '09 at 09:57
  • This worked for me http://stackoverflow.com/questions/4692981/c-sharp-blocking-a-folder-from-being-changed-while-processing/4693064#4693064 – Vbp Jul 13 '14 at 15:59
  • https://github.com/Tyrrrz/LockFile – ElektroStudios Dec 28 '22 at 23:52

2 Answers2

46

Simply open it exclusively:

using (FileStream fs = 
         File.Open("MyFile.txt", FileMode.Open, FileAccess.Read, FileShare.None))
{
   // use fs
}

Ref.

Update: In response to comment from poster: According to the online MSDN doco, File.Open is supported in .Net Compact Framework 1.0 and 2.0.

Mitch Wheat
  • 295,962
  • 43
  • 465
  • 541
  • 1
    Not sure this answers the question. OP is looking for the FileStream.Lock method, which doesn't exist in the compact framework. Lock prevents other processes from modifying the file, but still lets them read it. I think your method would block other processes completely. – MusiGenesis Sep 16 '09 at 10:32
  • @Mitch: and your answer may be exactly what he needs, but if he's trying to find a WinMo way to do what FileStream.Lock does (block write access but not read access, and lock a byte range in the file) then it isn't. – MusiGenesis Sep 16 '09 at 10:41
  • @MitchWheat If i open a lot of file streams like this,will this result in memory loss or reduce system performance? – techno Dec 16 '12 at 14:26
0

FileShare.None would throw a "System.IO.IOException" error if another thread is trying to access the file.

You could use some function using try/catch to wait for the file to be released. Example here.

Or you could use a lock statement with some "dummy" variable before accessing the write function:

    // The Dummy Lock
    public static List<int> DummyLock = new List<int>();

    static void Main(string[] args)
    {
        MultipleFileWriting();
        Console.ReadLine();
    }

    // Create two threads
    private static void MultipleFileWriting()
    {
        BackgroundWorker thread1 = new BackgroundWorker();
        BackgroundWorker thread2 = new BackgroundWorker();
        thread1.DoWork += Thread1_DoWork;
        thread2.DoWork += Thread2_DoWork;
        thread1.RunWorkerAsync();
        thread2.RunWorkerAsync();
    }

    // Thread 1 writes to file (and also to console)
    private static void Thread1_DoWork(object sender, DoWorkEventArgs e)
    {
        for (int i = 0; i < 20; i++)
        {
            lock (DummyLock)
            {
                Console.WriteLine(DateTime.Now.ToString("dd/MM/yyyy hh:mm:ss") + " -  3");
                AddLog(1);
            }
        }
    }

    // Thread 2 writes to file (and also to console)
    private static void Thread2_DoWork(object sender, DoWorkEventArgs e)
    {
        for (int i = 0; i < 20; i++)
        {
            lock (DummyLock)
            {
                Console.WriteLine(DateTime.Now.ToString("dd/MM/yyyy hh:mm:ss") + " -  4");
                AddLog(2);
            }
        }
    }

    private static void AddLog(int num)
    {
        string logFile = Path.Combine(Environment.CurrentDirectory, "Log.txt");
        string timestamp = DateTime.Now.ToString("dd/MM/yyyy hh:mm:ss");

        using (FileStream fs = new FileStream(logFile, FileMode.Append,
            FileAccess.Write, FileShare.None))
        {
            using (StreamWriter sr = new StreamWriter(fs))
            {
                sr.WriteLine(timestamp + ": " + num);
            }
        }

    } 

You can also use the "lock" statement in the actual writing function itself (i.e. inside AddLog) instead of in the background worker's functions.

Maverick Meerkat
  • 5,737
  • 3
  • 47
  • 66