---
title: "How can you open a file with exclusive access so no other process can read/write it?"  
description: "How can you open a file with exclusive access so no other process can read/write it?"  
author: "ICSM Computer"  
published: 2025-05-11  
updated: 2025-05-30  
canonical: https://www.mindstick.com/forum/161602/how-can-you-open-a-file-with-exclusive-access-so-no-other-process-can-read-write-it  
category: "c#"  
tags: ["c#", "file handling"]  
reading_time: 2 minutes  

---

# How can you open a file with exclusive access so no other process can read/write it?

How can you open a [file](https://www.mindstick.com/articles/59/encrypting-and-decrypting-files-using-c-sharp) with exclusive [access](https://www.mindstick.com/articles/12994/how-foreigners-can-access-blocked-websites-in-china) so no other [process](https://yourviews.mindstick.com/story/1525/7-important-factors-that-may-affect-the-learning-process) can read/write it?

## Replies

### Reply by ICSM Computer

To open a file with **exclusive access** in C#, you can use the `FileStream` constructor and explicitly set the `FileShare` mode to `None`.

## Example: Open a file with exclusive access

```cs
using System;
using System.IO;

public class ExclusiveFileAccess
{
    public static FileStream OpenExclusive(string path)
    {
        return new FileStream(
            path,
            FileMode.OpenOrCreate,     // Open existing or create new
            FileAccess.ReadWrite,      // Allow reading and writing
            FileShare.None             // Do not allow any other access
        );
    }
}
```

### `FileShare.None` means:

**No other process or thread** can open the file — not for reading, writing, or even deleting — until the stream is closed.

## Usage

```cs
try
{
    using var stream = ExclusiveFileAccess.OpenExclusive("data.txt");
    using var writer = new StreamWriter(stream);
    writer.WriteLine("This file is locked for exclusive access.");
}
catch (IOException ex)
{
    Console.WriteLine("Could not access file exclusively: " + ex.Message);
}
```

## Summary of `FileShare` Options

| FileShare Option | Allows Other Processes To... |
| --- | --- |
| `None` | No access (exclusive) |
| `Read` | Read only |
| `Write` | Write only |
| `ReadWrite` | Read and write |
| `Delete` | Delete |

## Notes

- **Always use a** `using` **block or** `Dispose()` to release the lock promptly.
- On Windows, if another process tries to open the file while you have it open with `FileShare.None`, it will throw an `IOException`.
- On **Linux**, file locking behavior is advisory (not enforced by the OS unless using additional mechanisms like `fcntl`).


---

Original Source: https://www.mindstick.com/forum/161602/how-can-you-open-a-file-with-exclusive-access-so-no-other-process-can-read-write-it

Copyright © MindStick Software Pvt. Ltd. This Markdown version is provided for developers, AI systems, and offline reading.
