Access to Path Denied - Vb.Net - 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.

Related

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")

Rendering and saving report file to .pdf

I made app to create reports and save it as .pdf At mine computer after creating report i use this code to save it as .pdf
Try
My.Computer.FileSystem.WriteAllBytes("C:\" & Form1.TextBox2.Text & "_Report.pdf", ReportViewer1.LocalReport.Render("pdf"), False)
MessageBox.Show("Exported to .pdf file on at location C:\", "Note ", MessageBoxButtons.OK, MessageBoxIcon.Information)
Catch ex As Exception
End Try
But when i send the application to someone else it won't create this the .pdf on other computer. What is required to be installed ?
On modern windows computers normal users don't have the permission to access the "C:\" directory directly. When trying to access it with your code, you get a exception, which is in your example code silently ignored.
A better way is to store the file in the users personal folder. You can use the GetFolderPath method to get it:
Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments)
also see: http://msdn.microsoft.com/de-de/library/system.environment.specialfolder%28v=vs.110%29.aspx?cs-save-lang=1&cs-lang=vb

How To Verify Network Folder Access

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

Testing if I have full read/write access to a file in VB .NET 4.5 before processing it

I'm writing a windows service which runs as the local system account. I'm trying to make sure if I have full read/write access to a file beginning to process it any further. Here is my code:
Dim FullPath As String
FullPath = "C:\directory\file.txt"
Dim ps As Security.PermissionSet
ps = New Security.PermissionSet(Security.Permissions.PermissionState.Unrestricted)
ps.AddPermission(New Security.Permissions.FileIOPermission(Security.Permissions.FileIOPermissionAccess.AllAccess, FullPath))
ps.AddPermission(New Security.Permissions.FileIOPermission(Security.Permissions.FileIOPermissionAccess.AllAccess, IO.Path.GetDirectoryName(FullPath)))
Try
ps.Demand()
Catch ex As Security.SecurityException
System.Diagnostics.EventLog.WriteEntry("ShopLink", "File " + FullPath + " will not be parsed. " + ex.Message)
Exit Sub
Catch ex As Exception
System.Diagnostics.EventLog.WriteEntry("ShopLink", "File " + FullPath + " will not be parsed. " + ex.Message)
Exit Sub
End Try
Then I set the full access permissions for the file to "Deny" for the user account my service is running as. After executing, the code above doesn't throw any exceptions and allows file processing to begin. When the service later tries to change and/or delete the file, I get an "Access Denied" exception.
Any suggestions?
For this purpose i use thise small function:
Private Function HasAccess(ByVal ltFullPath As String)
Try
Using inputstreamreader As New StreamReader(ltFullPath)
inputstreamreader.Close()
End Using
Using inputStream As FileStream = File.Open(ltFullPath, FileMode.Open, FileAccess.ReadWrite, FileShare.None)
inputStream.Close()
Return True
End Using
Catch ex As Exception
Return False
End Try
End Function
In your case then:
If HasAccess(FullPath) ...
I have solved the problem by using My.Computer.FileSystem.DeleteFile to delete the file instead of Kill. My.Computer.FileSystem.DeleteFile was executed without problems after successfully demanding full read/write access to the file in the way described above, while Kill consistently threw an "Access denied" exception.
Using "Kill"... I know this is a very old thread but I'll add this in case anyone stumbles on it like I did. I was working on some old VB6 legacy code. One of my clients users was getting a runtime exception during a file open after a kill. The code was "Killing" the file and then rebuilding it from scratch with binary data held in memory. It tuns out that the "Kill" function triggered the user's anti-virus software which locked the file long enough to cause the next "Open" statement to fail. I discovered this using an error logging utility (the name escapes me at the moment). The line in the error log file on the failed "Open" statement was that the file's status was "Delete pending" due to the user's anti-virus software.

IDatabaseCompact.Compact() on an used IWorkspace

I am writting an ArcMap-AddIn with vb.net. I got an error when trying to compact my IWorkspace(mdb), the error is:
COMException
You tried to open a database, which was already opened by the user
'ADMIN' on Computer 'XXXXXX'. Try it again when the database is
available.
On ESRI.ArcGIS.Geodatabase.IDatabaseCompact.Compact() on
MyProject.MyClass.CompactGDB(IWorkspace pWS)
How can i compact the used workspace?
There are 8 other functions which also used my workspace.
Any suggestions?
The Code:
' CompactGDB
Public Sub CompactGDB(ByVal pWS As IWorkspace)
Dim pDatabaseCompact As IDatabaseCompact
If (TypeOf pWS Is IDatabaseCompact) Then
pDatabaseCompact = CType(pWS, IDatabaseCompact)
If (pDatabaseCompact.CanCompact) Then
Try
pDatabaseCompact.Compact()
Catch ex As Exception
MessageBox.Show(ex.type & ex.Message & ex.StackTrace, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
End Try
End If
End If
End Sub
Found the solution:
Before calling the Compact() method make sure there are not any existing locks on the database.
If it is a file geodatabase then open the gdb directory in Windows Explorer and look for LOCK type files, they end in .lock.
For personal geodatabase there will be a .ldb file in the directory with the same name as the .mdb.
If you have a layer or table from the geodatabase loaded in the map
then you will not be able to remove all locks.
If another user is
accessing the geodatabase then you will not be able to remove all
locks.
If you are using arcobjects to temporarily access the
geodatabase then you need to use good practices and close any
geodatabase resources when the calling process ends. This includes
releasing all COM objects when you are finished with them.
Use the ComReleaser Class in ESRI.ArcGIS.ADF.Connection.Local namespace