To create a read-only file and enforce its protection programmatically, you can follow two main steps:
Create or write the file.
Set the file attribute or permissions to read-only.
Here’s how to do this in various environments:
C# (.NET)
using System.IO;
string filePath = "readonly.txt";
// Step 1: Create the file
File.WriteAllText(filePath, "This is a read-only file.");
// Step 2: Set it as read-only
File.SetAttributes(filePath, File.GetAttributes(filePath) | FileAttributes.ReadOnly);
This sets the read-only attribute at the file system level.
Any attempt to modify or delete the file without clearing the attribute will throw an exception.
import java.io.File;
import java.io.IOException;
File file = new File("readonly.txt");
try {
if (!file.exists()) {
file.createNewFile();
}
// Write content (if needed)
// Files.write(Paths.get("readonly.txt"), "This is a read-only file.".getBytes());
// Set to read-only
boolean success = file.setReadOnly();
if (!success) {
System.out.println("Failed to set file as read-only.");
}
} catch (IOException e) {
e.printStackTrace();
}
Uses the file system’s read-only flag.
Prevents writing via most standard APIs.
Python
import os
file_path = "readonly.txt"
# Step 1: Create/write the file
with open(file_path, 'w') as f:
f.write("This is a read-only file.")
# Step 2: Make it read-only
os.chmod(file_path, 0o444) # Read-only for everyone
0o444 sets read-only permissions for user, group, and others.
To make it writable again:
os.chmod(file_path, 0o644) # Owner can write
Linux / Bash
echo "This is a read-only file." > readonly.txt
chmod 444 readonly.txt
Prevents writes by anyone (owner, group, others).
To restore write permission for the owner: chmod 644 readonly.txt
Important Notes
Setting a file to read-only prevents writes via normal file operations.
It does not prevent deletion unless the parent directory is also protected or access control lists (ACLs) or file system security are used.
For stricter enforcement, consider setting file permissions via ACLs or locking via OS-level APIs.
Markdown for AI
A clean, structured version of this page for AI assistants and LLMs.
We use cookies to ensure you have the best browsing experience on our website. By using our site, you
acknowledge that you have read and understood our
Cookie Policy &
Privacy Policy.
To create a read-only file and enforce its protection programmatically, you can follow two main steps:
Here’s how to do this in various environments:
C# (.NET)
To remove the read-only flag later:
Java
Python
0o444sets read-only permissions for user, group, and others.To make it writable again:
Linux / Bash
chmod 644 readonly.txtImportant Notes