I started making a file manager which scans a folder selected by user through folderbrowserdialog in vb.net, extract the extentions of every file in every directory or subdirectory using GetFiles() Method with SearchOption.AllDirectories. I am having an UnauthorizedAccessException when it scans the Recycle Bin Folder in logical drive whereas i have seen Softwares like WinRar or R-Studio Scanning and showing every directory without having an exception or error. Following is my code:
Public Sub WriteExtentionsToFile()
Try
Title_Window.FolderBrowserDialog.ShowDialog()
Dim Path As String = Title_Window.FolderBrowserDialog.SelectedPath
'Getting FilesNames
Dim FileNames As String() = GetFilesNames(Path)
Title_Window.LblStatusBar.Text = "File Names Saved"
Dim MaximumForProgressBar As Integer = FileNames.Length
Title_Window.ToolStripProgressBar1.Maximum = MaximumForProgressBar
Title_Window.ToolStripProgressBar1.Step = 1
'Getting Extentions
Dim ExtentionsList As New List(Of String)
For Each item In FileNames
ExtentionsList.Add(System.IO.Path.GetExtension(item))
Next
'Deleting Duplicate Extentions
Dim NoDuplicateExtentionList As New List(Of String)
Dim ExtentionReadFromFile As String() = ReadExtentionsFromFile()'Another Function in my Class Which Reads previously saved extentions in a file and store them in an array
For Each item In ExtentionReadFromFile
NoDuplicateExtentionList.Add(item)
Next
For Each E In ExtentionsList
Dim LastIndexOfDot As Integer = E.LastIndexOf(".")
E = E.Remove(0, LastIndexOfDot + 1)
If NoDuplicateExtentionList.Contains(E.ToLower) = False Then
NoDuplicateExtentionList.Add(E.ToLower)
My.Computer.FileSystem.WriteAllText("d:\ExtentionsList.txt", E.ToString & vbCrLf, True)
End If
Next
MessageBox.Show("Writing Process Completed", "Success")
Catch ex As UnauthorizedAccessException
Dim Buttons As MessageBoxButtons = MessageBoxButtons.AbortRetryIgnore
Dim result As DialogResult
MessageBox.Show(ex.ToString, "Access Denied", Buttons)
If result = Windows.Forms.DialogResult.Ignore Then
'What should be Done Here????
ElseIf result = Windows.Forms.DialogResult.Abort Then
'What should be Done Here????
Else
'What should be Done Here????
End If
Catch ex As Exception
MessageBox.Show(ex.ToString)
End Try
End Sub
What should be the solution for thsi problem? Is this about getting the permissions through FileIoPermission Class or something else??
Related
I want to move multiple files from one directoy to anoher. I use 'My.Computer.FileSystem.MoveFile' and that works fine but it handles one file at a time. So, for every already existing file in that directory I get a warning (ie. 'File already exists') instead of one warning for the batch. Is it posible to get one warning for all the moved files?
For i = .Items.Count - 1 To 0 Step -1
Dim map = .Items.Item(i).SubItems(COL_MAP).Text
Dim bestandHernoemd = .Items.Item(i).SubItems(COL_HERNOEMD).Text
Dim bestandOrigineel = .Items.Item(i).SubItems(COL_ORIGINEEL).Text
Try
My.Computer.FileSystem.MoveFile(map & bestandOrigineel, My.Settings.OPTIE_OvernemenStandaardMapNaam & bestandHernoemd, Microsoft.VisualBasic.FileIO.UIOption.AllDialogs, Microsoft.VisualBasic.FileIO.UICancelOption.ThrowException)
.Items.RemoveAt(i)
Catch ex As Exception
foutLijst.Add(bestandOrigineel & ": " & ex.Message)
End Try
Next
And if you want to copy files recursively ( all folders, subfolders, files or subfiles ) from one source to destination, you can use the below sub procedure. No Warning applied and shall overwrite the destination.
Public Sub CopyDirectory(ByVal sourcePath As String, ByVal destinationPath As String)
Dim sourceDirectoryInfo As New System.IO.DirectoryInfo(sourcePath)
'If the destination folder doesn't exist then create it'
If Not System.IO.Directory.Exists(destinationPath) Then
'Obs, folder doesn't exist, create one please :)'
System.IO.Directory.CreateDirectory(destinationPath)
End If
Dim fileSystemInfo As System.IO.FileSystemInfo
For Each fileSystemInfo In sourceDirectoryInfo.GetFileSystemInfos
Dim destinationFileName As String = System.IO.Path.Combine(destinationPath, fileSystemInfo.Name)
'Now check whether its a file or a folder and take action accordingly
If TypeOf fileSystemInfo Is System.IO.FileInfo Then
System.IO.File.Copy(fileSystemInfo.FullName, destinationFileName, True)
Else
' Recursively call the method to copy all the nested folders
CopyDirectory(fileSystemInfo.FullName, destinationFileName)
End If
Next
End Sub
I am new to VB.net and I am trying to write a forms app that works with Autodesk Inventor.
Unfortunately, every time I close Inventor, the "Inventor.exe" process still stays. I didn't realize this while debugging and I only realized this when I checked the task manager after the whole system started to lag.
Killing every process with the same name is fairly simple, but the issue is that the end user might have separate documents open in another Inventor window. So I need to write a function that only kills the Inventor processes that don't have a window open.
Public Class Form1
Dim _invApp As Inventor.Application
Dim _started As Boolean = False
Public Sub New()
' This call is required by the designer.
InitializeComponent()
' Add any initialization after the InitializeComponent() call.
Try
_invApp = Marshal.GetActiveObject("Inventor.Application")
Catch ex As Exception
Try
Dim invAppType As Type = _
GetTypeFromProgID("Inventor.Application")
_invApp = CreateInstance(invAppType)
_invApp.Visible = True
'Note: if you shut down the Inventor session that was started
'this(way) there is still an Inventor.exe running. We will use
'this Boolean to test whether or not the Inventor App will
'need to be shut down.
_started = True
Catch ex2 As Exception
MsgBox(ex2.ToString())
MsgBox("Unable to get or start Inventor")
End Try
End Try
End Sub
Another section where I start a process, which is a specific 3D model file.
Public Sub SaveAs(oTemplate As String)
'define the active document
Dim oPartDoc As PartDocument = _invApp.ActiveDocument
'create a file dialog box
Dim oFileDlg As Inventor.FileDialog = Nothing
Dim oInitialPath As String = System.IO.Path.GetFullPath("TemplatesResources\" & oTemplate)
_invApp.CreateFileDialog(oFileDlg)
'check file type and set dialog filter
If oPartDoc.DocumentType = kPartDocumentObject Then
oFileDlg.Filter = "Autodesk Inventor Part Files (*.ipt)|*.ipt"
ElseIf oPartDoc.DocumentType = kAssemblyDocumentObject Then
oFileDlg.Filter = "Autodesk Inventor Assembly Files (*.iam)|*.iam"
ElseIf oPartDoc.DocumentType = kDrawingDocumentObject Then
oFileDlg.Filter = "Autodesk Inventor Drawing Files (*.idw)|*.idw"
End If
If oPartDoc.DocumentType = kAssemblyDocumentObject Then
oFileDlg.Filter = "Autodesk Inventor Assembly Files (*.iam)|*.iam"
End If
'set the directory to open the dialog at
oFileDlg.InitialDirectory = "C:\Vault WorkSpace\Draft"
'set the file name string to use in the input box
oFileDlg.FileName = "######-AAAA-AAA-##"
'work with an error created by the user backing out of the save
oFileDlg.CancelError = True
On Error Resume Next
'specify the file dialog as a save dialog (rather than a open dialog)
oFileDlg.ShowSave()
'catch an empty string in the imput
If Err.Number <> 0 Then
MessageBox.Show("Any changes made from here will affect the original template file!", "WARNING", MessageBoxButtons.OK, MessageBoxIcon.Warning, MessageBoxDefaultButton.Button1, MessageBoxOptions.ServiceNotification)
ElseIf oFileDlg.FileName <> "" Then
Dim MyFile As String = oFileDlg.FileName
'save the file
oPartDoc.SaveAs(MyFile, False)
'open the drawing document
System.Diagnostics.Process.Start(oInitialPath & ".idw")
Dim oFinalPath As String = oPartDoc.FullFileName
MessageBox.Show(oFinalPath, "", MessageBoxButtons.OK, MessageBoxIcon.None, MessageBoxDefaultButton.Button1, MessageBoxOptions.ServiceNotification)
MessageBox.Show("Loaded", "", MessageBoxButtons.OK, MessageBoxIcon.None, MessageBoxDefaultButton.Button1, MessageBoxOptions.ServiceNotification)
Dim oDrawingDoc As DrawingDocument = _invApp.Documents.ItemByName(oInitialPath & ".idw")
'oDrawingDoc.SaveAs()
End If
End Sub
Any help is appreciated.
Thanks
At the end on your form, probably FormClosed, add the following:
Private Sub Form1_FormClosed(sender As Object, e As FormClosedEventArgs) Handles Me.FormClosed
If (_invApp Is Nothing) Then Return ' if empty, then no action needed
_invApp.Quit()
Marshal.ReleaseComObject(_invApp)
_invApp = Nothing
System.GC.WaitForPendingFinalizers()
System.GC.Collect()
End Sub
This should make .NET release and properly dispose the COM Object for Inventor.
And consider declare the Inventor variable and assign Nothing/null, it's safer (avoid mistakes)
Dim _invApp As Inventor.Application = Nothing
i have been trying to figure out how to delete a .txt file that constantly change name exept the first 4 ex: THISTEXT-123-45.txt where THISTEXT stays the same but -123-45 changes.
I have found a way to detect it, but i don't know how to delete it.
Dim paths() As String = IO.Directory.GetFiles("C:\", "THISTEXT*.txt")
If paths.Length > 0 Then
Anyone knows the command line to delete that special .txt file?
I am using Visual Basic on visual studio 2013 framework 3.5.
Use the Delete method of System.IO.
Assuming you have write access to C:\
Dim FileDelete As String
FileDelete = "C:\testDelete.txt"
If System.IO.File.Exists( FileDelete ) = True Then
System.IO.File.Delete( FileDelete )
MsgBox("File Deleted")
End If
Deleting a file is quite simple - but dangerous! So be very careful when you're trying out this code.
Edit
To delete all file use *(asterisk) followed with the file extension
example C:\*.txt"
For multiple files
Dim FileDelete As String
FileDelete = "C:\"
For Each FileDelete As String In IO.Directory.GetFiles(FileDelete & "THISTEXT*.txt")
File.Delete(FileDelete)
Next
If you read the MSDN page on GetFiles, you will realize that you have the file name and path in your paths array. You can then iterate through the array deleting your matches.
Dim x as Integer
Dim paths() as String = IO.Directory.GetFiles("C:\", "THISTEXT*.txt")
If paths.Length > 0 Then
For x = 0 to paths.Length -1
IO.File.Delete(paths(x))
Next
End If
To build on the feedback you provided to Omar's answer, it appears that your file path and file name are separate.
You cannot provide them separated by a comma, as commas denote separate parameters passed to a subroutine or function.
To fix this, you need to concatenate them, for example:
Dim fileName As String = "foo.txt"
Dim filePath As String = "C:\"
Dim FileToDelete As String = fileName + filePath
To delete a single .*txt file if it exists:
If (deleteFile("C:\")) Then
MsgBox("File deletion successful")
Else
MsgBox("File couldn't be deleted with the following error: " + exception)
End If
alternatively with concatenation:
If (deleteFile("C:\") Then
MsgBox("File deletion successful")
Else
MsgBox("File couldn't be deleted with the following error: " + exception)
End If
Dim exception As String 'Place this at the beginning of your app's class.
Dim path As String = "C:\"
If (deleteFile(path)) Then
MsgBox("File deletion successful")
Else
MsgBox("File couldn't be deleted with the following error: " + exception)
End If
Private Function deleteFile(ByVal dir) As Boolean
Dim fileToRemove As String
Try
Dim paths() As String = IO.Directory.GetFiles(dir, "THISTEXT*.txt")
For i As Integer = 0 To paths.Length
fileToRemove = paths(i).ToString
System.IO.File.Delete(fileToRemove)
If (Not System.IO.File.Exists(fileToRemove)) Then
Return True
Else
exception = "Unknown error."
Return False
End If
Next
Return False
Catch ex As Exception
exception = ex.Message
Return False
End Try
Return False
End Function
The above function checks if the file exists, if it does it tries to delete it. If the file cannot be deleted, or an error occurs (which is handled), the Function returns False.
Simple example:
For Each path As String In IO.Directory.GetFiles("C:\", "THISTEXT*.txt")
Try
System.IO.File.Delete(path)
Catch ex As Exception
MessageBox.Show(path, "Unable to Delete File")
End Try
Next
I am trying to search if a text file in a sub-folder exists.
This is the code I am using:
'Checks the program's root folder to see if the root folder exists.
Dim FolderName = New DirectoryInfo(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), "Cake Orders\" & TextBox1.Text))
Dim McKnwoll As String = Path.Combine(FolderName.FullName, Trim(TextBox2.Text) & (" ") & Trim(TextBox3.Text) + ".RTO")
If Not McKnwoll.Exists Then
‘Message to user that file does not exist in sub-folder
Else
‘Message to user that file does exists in sub-folder
End If
I am getting an error that 'Exists' is not a member of 'String'. How can I re-work my code to check if the text file whose name is in the format of "TextBox2.Text & (" ") & TextBox3.Text + ".RTO"; exists.
I am using Visual Basic 2010 Express. Thank you.
File.Exists returns a Boolean indicating whether a file at a certain path exists:
If File.Exists(pathToFile) Then
...
End If
Be sure to include Imports System.IO at the top of your source code file.
You seem quite new in programming. Welcome.
That error message you got ('Exists' is not a member of 'String') tells you exactely what is wrong: You try to ask a string (some text) whether it exists, but what you like to do is to ask a file whether it exists.
The class that provides information about a file is called "FileInfo", and FileInfo has an "Exists" property that you can call:
Dim myFileInfo As New FileInfo(McKnwoll)
If myFileInfo.Exists Then
'do something
End If
That's the object oriented answer, Heinzi's more service oriented one but works, of course, too.
There have been several other small issues I noticed with your code, e.g.
"Cake Orders\" & TextBox1.Text
does not use Path.Combine but makes a string concatenation using fix a "\" as directory separater. Or that the DirectoryInfo is not really used here, the string to the folder is enough.
You also try to handle 3 different issues (reading the values from the user interface, constructing the fullname of the file, checking whether the file exists) in one single code block. I would split them into 3 different ones (actually 4, I would add another one for displaying error messages).
Your simple few lines of codes could be complicated like this ;-)
Imports System.IO
Imports System.Text
Public Class Form1
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
ReadFileIfPossible(TextBox1.Text, TextBox2.Text, TextBox3.Text)
End Sub
Private Sub ReadFileIfPossible(subfolder As String, part1 As String, part2 As String)
'Get the path to the RTO file
Dim myFilePath As String = Nothing
Try
myFilePath = GetRtoFilePath(subfolder, part1, part2)
Catch ex As Exception
DisplayErrorMessage("Error constructing file name! Please check the values of TextBox1, TextBox2 and TextBox3.")
Return
End Try
'Get the file info
Dim myFile As FileInfo = Nothing
Try
myFile = New FileInfo(myFilePath)
Catch ex As Exception
DisplayErrorMessage(ex.Message)
Return
End Try
'Check whether it exists
Dim myExists As Boolean = False
Try
myExists = myFile.Exists 'it's IO, everything might throw an exception...
Catch ex As Exception
DisplayErrorMessage(ex.Message)
Return
End Try
'Display message if not found
If (Not myExists) Then
DisplayErrorMessage("File ""{0}"" could not be found!", myFilePath)
Return
End If
'Read the file
Dim myLines As String() = Nothing
Try
myLines = File.ReadAllLines(myFile.FullName, New UTF8Encoding(True))
Catch ex As Exception
DisplayErrorMessage(ex.Message)
Return
End Try
'Do something with it...
End Sub
Private Shared Function GetRtoFilePath(subfolder As String, part1 As String, part2 As String) As String
'Check args
If (subfolder Is Nothing) Then Throw New ArgumentNullException("subfolder")
If (part1 Is Nothing) Then Throw New ArgumentNullException("part1")
If (part2 Is Nothing) Then Throw New ArgumentNullException("part2")
'Normalize args
part1 = part1.Trim()
part2 = part2.Trim()
'Build path
Dim myDesktopPath As String = Environment.GetFolderPath(Environment.SpecialFolder.Desktop)
Dim myFolderPath As String = Path.Combine(myDesktopPath, "Cake Orders")
myFolderPath = Path.Combine(myFolderPath, subfolder)
Dim myFileName As String = String.Format("{0} {1}.RTO", part1, part2)
Dim myResult As String = Path.Combine(myFolderPath, myFileName)
myResult = Path.GetFullPath(myResult)
'Return result
Return myResult
End Function
Private Sub DisplayErrorMessage(message As String, ParamArray args As Object())
Dim myMsg As String = String.Format(message, CType(args, Object()))
MsgBox(myMsg, MsgBoxStyle.OkOnly, "Error")
End Sub
End Class
Have fun.
I should know better than to not give enough information/good information when asking for help. I have another question which I need to delete/link or merge here... any comment on how to do that would be great.
So the problem is I am trying to write a simple app (yeah, right) to locate a specific file on the local HDD. There WILL be multiple instances of the file (backups etc.) and I want to find each. Issues are that I cannot know how many local hdd there are and I cannot know what directory the file might be in.
So I wanted to
iterate through all fixed HDD
search the hdd for the file (I always know the name of the file)
I search HDD like this...
For Each drive As IO.DriveInfo In IO.DriveInfo.GetDrives
If drive.DriveType.ToString = "Fixed" Then
So if the found hdd is fixed I do this...
Try
For Each filename As String In IO.Directory.GetFiles(hdd, "user.config", IO.SearchOption.AllDirectories)
The issue is that I throw an exception, I have the for block above in a try catch, the exception is caught and the code exits.
OK, so I guess this is to be expected. Any suggestions on how to avoid this? Meaning I know I will run across files/directories I do not have permission for, how do I carry on and ignore what I don't care about?
FULL CODE LISTING
Private Sub Command1_Click(sender As System.Object, e As System.EventArgs) Handles Command1.Click
'variable to hold each hdd name eg: c:\
Dim hdd As String
Dim directories As Integer = 0
Dim files As Integer = 0
Try
For Each drive As IO.DriveInfo In IO.DriveInfo.GetDrives
If drive.DriveType.ToString = "Fixed" Then
'asign the variable hdd a name for this run through
hdd = drive.Name
'assign label value for directories
directories = directories + 1
Label6.Text = directories.ToString
Me.Refresh()
'search the hdd for the file user.config
Try
For Each filename As String In IO.Directory.GetFiles(hdd, "user.config", IO.SearchOption.AllDirectories)
Me.Refresh()
' 'assign label value for files
files = files + 1
Label2.Text = files.ToString
Me.Refresh()
' 'variable to hold the path for each found file
Dim file As String = IO.Path.GetFullPath(filename)
' 'update file checking label
Label4.Text = file.ToString
' 'add each found file to the list
List1.Items.Add(file)
Next
Catch ex As Exception
End Try
End If
Next
Catch ex As Exception
MsgBox(ex.ToString)
End Try
'iterate through each found drive
End Sub
You need to write it out long-wise because you need to handle the IO security issues. And of course a recursive function.
Called by:
FindFileOnAllDrivesOfType(System.IO.DriveType.Fixed, "test.txt")
Methods:
Public Function FindFileOnAllDrivesOfType(ByVal DriveType As System.IO.DriveType, ByVal FileToFind As String) As List(Of String)
Dim AllLocations As New List(Of String)
For Each drive As IO.DriveInfo In IO.DriveInfo.GetDrives
If drive.DriveType = DriveType Then
AllLocations = FindFile(drive.ToString(), FileToFind)
End If
Next
Return AllLocations
End Function
Public Function FindFile(ByVal StartDirectory As String, ByVal FileToFind As String) As List(Of String)
Dim AllLocations As New List(Of String)
Try
For Each dirname As String In IO.Directory.GetDirectories(StartDirectory)
AllLocations.AddRange(FindFile(dirname, FileToFind))
Next
For Each filename As String In IO.Directory.GetFiles(StartDirectory, FileToFind, IO.SearchOption.TopDirectoryOnly)
AllLocations.Add(filename)
Next
Catch ex As Exception
' MessageBox.Show(ex.Message)
'Do nothing as we can't get a directory listing
End Try
Return AllLocations
End Function