Is folder writable?

OSVBNET 1,386 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.

VB
VB
An object-oriented programming language developed by Microsoft that is implemented on the .NET Framework. Previously known as Visual Basic .NET.
2,778 questions
{count} votes

Accepted answer
  1. Jiachen Li-MSFT 33,446 Reputation points Microsoft Vendor
    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.

    0 comments No comments

0 additional answers

Sort by: Most helpful

Your answer

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