How to Check for Permissions to Write to a Directory or File

How do you check for permissions to write to a directory or file?

UPDATE:

Modified the code based on this answer to get rid of obsolete methods.

You can use the Security namespace to check this:

public void ExportToFile(string filename)
{
var permissionSet = new PermissionSet(PermissionState.None);
var writePermission = new FileIOPermission(FileIOPermissionAccess.Write, filename);
permissionSet.AddPermission(writePermission);

if (permissionSet.IsSubsetOf(AppDomain.CurrentDomain.PermissionSet))
{
using (FileStream fstream = new FileStream(filename, FileMode.Create))
using (TextWriter writer = new StreamWriter(fstream))
{
// try catch block for write permissions
writer.WriteLine("sometext");


}
}
else
{
//perform some recovery action here
}

}

As far as getting those permission, you are going to have to ask the user to do that for you somehow. If you could programatically do this, then we would all be in trouble ;)

How to check write permissions of a directory in java?

if you just want to check if you can write:

File f = new File("path");
if(f.canWrite()) {
// write access
} else {
// no write access
}

for checking read access, there is a function canRead()

Checking for directory and file write permissions in .NET

The answers by Richard and Jason are sort of in the right direction. However what you should be doing is computing the effective permissions for the user identity running your code. None of the examples above correctly account for group membership for example.

I'm pretty sure Keith Brown had some code to do this in his wiki version (offline at this time) of The .NET Developers Guide to Windows Security. This is also discussed in reasonable detail in his Programming Windows Security book.

Computing effective permissions is not for the faint hearted and your code to attempt creating a file and catching the security exception thrown is probably the path of least resistance.

How to check write permissions of a directory in java? Can we change it?

The File.canWrite() method is behaving as its specification says it should:

Returns: true if and only if the file system actually contains a file denoted by this abstract pathname and the application is allowed to write to the file; false otherwise.

(Emphasis added).

It is returning false because the object is not a file.


If you are using Java 7 (or later), one solution would be to use Files.getAttribute to retrieve the relevant attribute(s) to determine the access. Note that the attribute you use may be operating system specific. (I'm sure Google could find examples for you.)

Bash - check if I have write permissions to parent of the any directory path

If I understand the question correctly, you want to check whether you have write access to the directory you want to create a subdirectory of, i.e. before creating /opt/some/path1/ you'd check write access to /opt/some/. You can do that by using the dirname command to get the parent directory's path, then using the -w test on that. Note that mkdir still might fail for reasons other than permissions on the parent directory, so you still need to check it for errors. Something like this:

dirToCreate=/opt/some/path1/
if [ ! -w "$(dirname "$dirToCreate")" ]; then
echo "Insufficient permissions to create $dirToCreate" >&2
else
mkdir "$dirToCreate" || {
echo "Error creating $dirToCreate (due to something other than permissions)" >&2
}
fi

Makefile: Check write permission to directory

Shell's /bin/test or /bin/[ will let you /bin/test -d /path/to/foo -a -w /path/to/foo, even if make doesn't by itself.

An alternate way to make a directory accessible is to try to create it with mkdir -p before testing whether it's writable. I've been known to do the following:

mkdir -p ${TARGETDIR} && test -w ${TARGETDIR}

If the first command fails, the second isn't tried. If the directory already exists, mkdir -p will succeed.

How to check permission is granted for a directory path and won't thorow EACCES error?


try {
Process p = new ProcessBuilder("ls", "-l", "-s", dir.getCanonicalPath()).start();

String line;
ArrayList<String> lineOut = new ArrayList<>();

BufferedReader error = new BufferedReader(new InputStreamReader(p.getErrorStream()));
while ((line = error.readLine()) != null) {
Log.e(TAG, "ls error = "+line);
}
error.close();

BufferedReader input = new BufferedReader(new InputStreamReader(p.getInputStream()));
while ((line = input.readLine()) != null) {
lineOut.add(line);
}

input.close();

String[] strings = lineOut.toArray(new String[]{});
List<FilesLS.FileEntry> fileEntries = FilesLS.processNewLines(strings);
for(FilesLS.FileEntry file : fileEntries){
Log.d(TAG, file.name +" = " + file.permissions);
}

} catch (IOException e) {
e.printStackTrace();
}

And some edits to this class

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public final class FilesLS {
/**
* Entry type: File
*/
public static final int TYPE_FILE = 0;
/**
* Entry type: Directory
*/
public static final int TYPE_DIRECTORY = 1;
/**
* Entry type: Directory Link
*/
public static final int TYPE_DIRECTORY_LINK = 2;
/**
* Entry type: Block
*/
public static final int TYPE_BLOCK = 3;
/**
* Entry type: Character
*/
public static final int TYPE_CHARACTER = 4;
/**
* Entry type: Link
*/
public static final int TYPE_LINK = 5;
/**
* Entry type: Socket
*/
public static final int TYPE_SOCKET = 6;
/**
* Entry type: FIFO
*/
public static final int TYPE_FIFO = 7;
/**
* Entry type: Other
*/
public static final int TYPE_OTHER = 8;
/**
* Device side file separator.
*/
public static final String FILE_SEPARATOR = "/"; //$NON-NLS-1$
/**
* Regexp pattern to parse the result from ls.
*/
private static Pattern sLsPattern = Pattern
.compile("^([bcdlsp-][-r][-w][-xsS][-r][-w][-xsS][-r][-w][-xstST])\\s+(\\S+)\\s+ (\\S+)\\s+(\\d{4}-\\d\\d-\\d\\d)\\s+(\\d\\d:\\d\\d)\\s+(.*)$"); //$NON-NLS-1$ \s+([\d\s,]*)

public static List<FileEntry> processNewLines(String[] lines) {
List<FileEntry> listOfFiles = new ArrayList<FileEntry>();
for (String line : lines) {
// no need to handle empty lines.
if (line.length() == 0) {
continue;
}
// run the line through the regexp
Matcher m = sLsPattern.matcher(line);
if (m.matches() == false) {
continue;
}
// get the name
String name = m.group(6);
// get the rest of the groups
String permissions = m.group(1);
String owner = m.group(2);
String group = m.group(3);
// String size = m.group(4);
String date = m.group(4);
String time = m.group(5);
String info = null;
// and the type
int objectType = TYPE_OTHER;
switch (permissions.charAt(0)) {
case '-':
objectType = TYPE_FILE;
break;
case 'b':
objectType = TYPE_BLOCK;
break;
case 'c':
objectType = TYPE_CHARACTER;
break;
case 'd':
objectType = TYPE_DIRECTORY;
break;
case 'l':
objectType = TYPE_LINK;
break;
case 's':
objectType = TYPE_SOCKET;
break;
case 'p':
objectType = TYPE_FIFO;
break;
}
// now check what we may be linking to
if (objectType == TYPE_LINK) {
String[] segments = name.split("\\s->\\s"); //$NON-NLS-1$
// we should have 2 segments
if (segments.length == 2) {
// update the entry name to not contain the link
name = segments[0];
// and the link name
info = segments[1];
// now get the path to the link
String[] pathSegments = info.split(FILE_SEPARATOR);
if (pathSegments.length == 1) {
// the link is to something in the same directory,
// unless the link is ..
if ("..".equals(pathSegments[0])) { //$NON-NLS-1$
// set the type and we're done.
objectType = TYPE_DIRECTORY_LINK;
} else {
// either we found the object already
// or we'll find it later.
}
}
}
// add an arrow in front to specify it's a link.
info = "-> " + info; //$NON-NLS-1$;
}
FileEntry entry = new FileEntry();
entry.permissions = permissions;
entry.name = name;
// entry.size = size;
entry.date = date;
entry.time = time;
entry.owner = owner;
entry.group = group;
if (objectType == TYPE_LINK) {
entry.info = info;
}
listOfFiles.add(entry);
}
return listOfFiles;
}

public final static class FileEntry {
String name;
String info;
String permissions;
String size;
String date;
String time;
String owner;
String group;
int type;
}
}

Check directory permissions whether the user can create files in or not

Some implementation without getopts that may not be xactly what you want but can show you off how you could achieve similar result:

#!/usr/bin/env sh

# Logfile
LOG=storage_lab3il.log

# Main folder
folder=./lab_3il

# Erase log file
true >"$LOG"

# The permission files to write to depending if writable
permfile_writable="$folder/-dir_with_write_perm.rep"
permfile_readonly="$folder/-dir_without_write_perm.rep"

# Delete the permission files
rm -f -- "$permfile_writable" "$permfile_readonly" || true

# While there is a subfolder argument
while [ -n "$1" ]; do
subfolder="$1" && shift # pull subfolder argument

# Continue to next if subfolder is not a directory
[ ! -d "$folder/$subfolder" ] && continue

# Test if sub-folder argument is writable
if [ -w "$folder/$subfolder" ]; then
permfile="$permfile_writable"
perm=yes
else
permfile="$permfile_readonly"
perm=no
fi

# Append the sub-folder name
# in its corresponding permission file
echo "$subfolder" >>"$permfile"

# Log: Writable = yes|no sub-folder argument name
printf 'Writable = %s: %s\n' "$perm" "$subfolder" >>"$LOG"
done

C# Test if user has write access to a folder

That's a perfectly valid way to check for folder access in C#. The only place it might fall down is if you need to call this in a tight loop where the overhead of an exception may be an issue.

There have been other similar questions asked previously.



Related Topics



Leave a reply



Submit