Share via

Is folder writable?

OSVBNET 1,401 Reputation points
2022-06-17T00:20:36.907+00:00

Hello experts,
Need to check if (My.Application.Info.DirectoryPath) is writable or not?

Found many things like:
blah As FileIOPermission = New FileIOPermission(FileIOPermissionAccess.Write, My.Application.Info.DirectoryPath)
If (Security.SecurityManager.IsGranted(writePermission))...
or
Directory.GetAccessControl

But none is what I need:

It is possible that the app is burned to the CD/DVD and will run from optical disc, now my app's path is not writable!
Or running from SD cards with write-protect lock on!
Any .net method to check such scenarios?
Thanks.

Developer technologies | VB

Answer accepted by question author

Jiachen Li-MSFT 34,241 Reputation points Microsoft External Staff
2022-06-17T02:41:44.097+00:00

Hi @OSVBNET ,
You can test if the path is writable by a function like the following.

    Public Function IsDirectoryWritable(ByVal dirPath As String, Optional ByVal throwIfFails As Boolean = False) As Boolean  
        Try  
  
            Using fs As FileStream = File.Create(  
            Path.Combine(  
                dirPath,  
                Path.GetRandomFileName()  
            ),  
            1,  
            FileOptions.DeleteOnClose)  
            End Using  
            Return True  
        Catch  
            If throwIfFails Then  
                Throw  
            Else  
                Return False  
            End If  
        End Try  
    End Function  

Best Regards.
Jiachen Li

----------

If the answer is helpful, please click "Accept Answer" and upvote it.
Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

Was this answer helpful?

0 comments No comments

0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as 'Accepted' by the question author and 'Recommended' by moderators, which helps users know the answer solved the author's problem.