How To Verify Network Folder Access - vb.net

Goal
To verify if a user has access to write / delete files on a specific network folder. For example:
\\MyCompany\Department\DocumentCenter\ is the directory where all the files are stored for the document center program. If a user has access to this folder, he is able to add / edit / delete files. If not, an error is caught by my try-catch.
Current Solution
I have attempted to solve this by setting up a try-catch right before the user deletes the file. If the user encounters an error, he will get a message saying that he does not have access... I find this rather trivial and would like a more concrete way of determining if the user has access to this folder.
How do I verify if a user has access to this specified folder?

When attempting to add / edit / delete a file on the given directory, as mentioned, I provide a try catch like so:
Private Sub DeleteFile(ByVal Path As String)
Try
'Example of Path: \\MyCompany\Department\DocumentCenter\File.PDF
File.Delete(Path)
Catch ex As Exception
MsgBox("Cannot delete this file. Contact your system admnistrator to have access to this directory.")
End Try
End Sub

Related

Edit Settings.txt Document within Program Files directory during AutoCAD runtime

I am trying to store the AutoCAD users' settings in a directory under their Program Files. Originally, I had everything stored in the users favorites folder, but I wanted to keep all the plugin documents/files within the same directory. So, I have been trying all kinds of options to get admin rights during runtime, but still have not been successful. This is, more or less, what I just recently tested:
Public Shared Sub GetAdminAccess()
AppDomain.CurrentDomain.SetPrincipalPolicy(PrincipalPolicy.WindowsPrincipal)
Dim curIdentity As WindowsIdentity = WindowsIdentity.GetCurrent()
Dim principalPerm As PrincipalPermission = New PrincipalPermission(Nothing, "BUILTIN\Administrators")
principalPerm.Demand()
End Sub
<PrincipalPermissionAttribute(SecurityAction.Demand, Role:="BUILTIN\Administrators")>
Private Shared Sub CreateSettingsFile()
Try
IO.File.Create(SettingsFilePath)
SettingsFileData = DefaultFileData
Property_WindowsOnTop = True
Property_SaveBackups = False
Property_SkipCreateSite = False
Property_AlignmentZoomExtents = ToFullExtents
Property_SaveBackups_Method = _TxtValue_Generic_None
Property_SaveBackups_MainDirectoryPath = _TxtValue_Generic_None
Call SetUserSettings(SettingsFileData)
Call SetPropertySettings()
Catch IOE As IO.IOException
MsgBox(IOE.Message)
Catch Ex As Exception
MsgBox(Ex.Message)
End Try
End Sub
Many of my attempts have resulted with this same error:
"Application attempted to perform an operation now allowed by the security policy. To grant this application the required permission, contact your system administrator, or use the Microsoft.NET Framework Configuration tool.
If you click Continue, the application will ignore this error and attempt to continue.
Request for principal permission failed."
An app can't write to the Program Files folder without administrator rights. The program files folder (and subfolders under it) are admin protected to prevent programs from replacing installed executable code with a malicious equivalent. Just don't do that.
If want app-specific data, use the appData folder. You can access that folder using System.Environment.SpecialFolder.ApplicationData and Environment.GetFolderPath
Get comfortable with the SpecialFolder enumeration (and with System.IO.Path.Combine). They are the correct way to access all of the well-known folders in the Windows OS.

Visual Basic don't see application.evtx

I have a problem with "Application.evtx" file. Everytime I run my script I get the message box with "File not found" information and I don't know why. I ran Visual Studio as administrator. Help me with this one, please.
Imports System.IO
Module Module1
Sub Main()
Dim pathReadFile As String = "c:\Windows\System32\winevt\Logs\Application.evtx"
'Dim pathReadFile As String = "%windir%\Sysnative\winevt\Logs\Application.evtx"
'Dim pathReadFile As String = "D:\Dokumenty\MyTest.txt"
Try
If File.Exists(pathReadFile) Then
MsgBox("File found.")
Else
MsgBox("File not found.")
End If
Catch ex As Exception
End Try
End Sub
End Module
Don't use File.Exists(). Ever.
There are many reasons for this, but the one that impacts you right now is that it lies to you and tells you the file does not exist, even if the file actually does exist and the real problem is that you don't have permissions to use it. From the docs:
Return Value
Type: System.Boolean
true if the caller has the required permissions and path contains the name of an existing file; otherwise, false
Remember that normal users have extremely limited file system permissions outside of their own home folders, and even Administrator users need to explicitly run a process as elevated or UAC will just give them normal user permissions.
You have to handle the exception anyway if reading the file fails. Put your development effort into the exception handler.
While I'm here, you may also want to build your path like this:
Dim pathReadFile As String = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.System), "winevt\Logs\Application.evtx")

Cannot delete just created file

My application can create a directory, put a file in it from a ZIP file and then remove the ZIP file.
When I then try to delete that file, I get an Access Denied error even though nothing was done with it.
Here is the code:
File.WriteAllBytes(OpslagLocatieDocumenten + myTicketNummer.ToString + "\documenten.zip", op.Documenten)
Using zp As New ZipFile(OpslagLocatieDocumenten + myTicketNummer.ToString + "\documenten.zip")
zp.FlattenFoldersOnExtract = True
zp.ExtractAll(OpslagLocatieDocumenten + myTicketNummer.ToString, ExtractExistingFileAction.OverwriteSilently)
zp.Dispose()
End Using
Try
For Each itm As String In Directory.GetFiles(OpslagLocatieDocumenten + myTicketNummer.ToString)
Try
File.Delete(itm)
Catch ex As Exception
End Try
Next
Catch ex As Exception
End Try
It looks a bit messy right now, but that is for testing purposes.
In the for-next part, right after writing the file from the ZIP, I try to delete the files.
At the moment there are two files in the directory, one ZIP and one PDF document from the ZIP.
The first file in itm is the PDF, it errors with an ACCESS DENIED.
The second file in itm is the ZIP which gets deleted.
The PDF is 311 kb in size.
Via Windows explorer I can delete it without any problem, even with the application still running.
Why is my file being locked?
What can I do to by-pass or remove this lock?
rg,
Eric
Found the problem.
The file that was added to the ZIP had it's attribute set to READ ONLY.
So when the application writes the file, windows would, as it should, not allow the application to delete it.
Unfortunately, windows does allow to delete the file via windows explorer without a message that the file is read only.
Have you also tried the File.Kill(fileLocation) method?

Protect single file!

I'm trying to protect a folder and the files inside it.
I'm able to protect the folder itself, so that if somebody clicks on it he will get a message:
"You don't currently have permission to access this folder!"
But I can still access files in that folder. For example, if somebody knows the name of a file inside the folder he can type D:\ProtectedFolder\pdffile.pdf and he can open the file!
So, my question is:
Can I protect single files inside the folder?
This is the function that I use for folder lock:
Public Function Lock(ByVal folder As
String, ByVal user As String)
Dim FilePath As String = folder
Dim fs As FileSystemSecurity = File.GetAccessControl(FilePath)
fs.AddAccessRule(New FileSystemAccessRule(user,
FileSystemRights.ListDirectory,
AccessControlType.Deny))
fs.AddAccessRule(New FileSystemAccessRule(user,
FileSystemRights.FullControl,
AccessControlType.Deny))
File.SetAccessControl(FilePath, fs)
Return 0
End Function
Thanks!
You will also have to deny FileSystemRights.Read if you want to prevent that. And technically you have to make sure that the files inherited their rights from the folder.
Specify FileShare.None for File.Open. You can see my C# implementation of it here with full source code. Convert it to VB.NET if you'd like.
This is the message you receive when trying to open a file locked by the application:
I think that's what you're after.

Access to Path Denied - Vb.Net

I have this small file search engine here made in VB.NET:
ListBox1.Items.Clear()
ListBox3.Items.Clear()
ChDir("C:\")
Try
For Each foundFile As String In My.Computer.FileSystem.GetFiles( _
My.Computer.FileSystem.CurrentDirectory, _
FileIO.SearchOption.SearchAllSubDirectories, TextBox4.Text & "*.*")
ListBox1.Items.Add(foundFile)
ListBox3.Items.Add(foundFile)
Next
Catch ex As UnauthorizedAccessException
MsgBox("Could not access file or not enough priveledges")
End Try
It searches through your whole C:\ for the file you entered. Although the problem I get is that some directories get access denied or not existing directories. How can I fix this problem?
Thanks
Some directories simply cannot be accessed like this. Use a try/catch loop with an empty catch to swallow errors and get the files that you can.
Try
'code for testing goes here
Catch
End Try
The above code when implemented properly should work if no error is thrown, and if no error is thrown then nothing will happen.
By granting privileges to the denied directories, and closing the programs that are locking the files within the directories.
MSDN says that, within the context of the GetFiles Method, an UnauthorizedAccessException means that the user lacks necessary permissions. See http://msdn.microsoft.com/en-us/library/t71ykwhb(VS.80).aspx
I would imagine that some directories are reserved by the file system, and you are not allowed certain types of access regardless of your privileges.