Error "Could not locate part of the path" when renaming file - vb.net

I verified all the directory paths exist so I am completely at a loss here.
For Each i As Project.ImageryCaptureTask.FileProperties In t.FileCollection
Dim NewFilename As New FileInfo(Path.Combine(Root.FullName, i.LVItem.Text))
If NewFilename.Exists Then
' ...Things get done
Else
Try
i.FI.MoveTo(NewFilename.FullName) ' <- Error thrown here (obviously)
Catch IOEx As IOException
MsgBox(IOEx.Message & vbCr & vbCr & "Error renaming to " & NewFilename.FullName, vbOKOnly, IOEx.Source)
Catch Ex As Exception
MsgBox(Ex.Message & vbCr & vbCr & "Error renaming to " & NewFilename.FullName, vbOKOnly, IOEx.Source)
End Try
End If
Next
Edit
Sorry, I was trying to keep the question short and quick, but I failed to provide the key information about Root.FullName. Here is the snippet to show that.
' P.MainFolder.FullName is the DirectoryInfo instantiated from the FolderBrowserDialog
If Directory.Exists(P.MainFolder.FullName) Then
For Each t As Project.ImageryCaptureTask In P.TaskCollection
Dim SubFolder3DMapping As New DirectoryInfo(Path.Combine(P.MainFolder.FullName, (Val(t.TaskCreationDate) + t.OffsetDate).ToString & "_" & P.ProjectNumber & "_" & P.ProjectName & "_" & Project.ImageryCaptureTask.CapturingMethods.Aerial3DMapping.ToString.Insert(6, "_")))
Dim SubFolderPhotos As New DirectoryInfo(Path.Combine(P.MainFolder.FullName, (Val(t.TaskCreationDate) + t.OffsetDate).ToString & "_" & P.ProjectNumber & "_" & P.ProjectName & "_" & Project.ImageryCaptureTask.CapturingMethods.AerialPhotos.ToString.Insert(6, "_")))
Dim SubFolderVideos As New DirectoryInfo(Path.Combine(P.MainFolder.FullName, (Val(t.TaskCreationDate) + t.OffsetDate).ToString & "_" & P.ProjectNumber & "_" & P.ProjectName & "_" & Project.ImageryCaptureTask.CapturingMethods.AerialVideos.ToString.Insert(6, "_")))
If Not SubFolder3DMapping.Exists Then SubFolder3DMapping.Create()
If Not SubFolderPhotos.Exists Then SubFolderPhotos.Create()
If Not SubFolderVideos.Exists Then SubFolderVideos.Create()
Dim Root As DirectoryInfo = Nothing
Select Case True
Case t.CaptureMethod = Project.ImageryCaptureTask.CapturingMethods.Aerial3DMapping
Root = SubFolder3DMapping
Case t.CaptureMethod = Project.ImageryCaptureTask.CapturingMethods.AerialPhotos
Root = SubFolderPhotos
Case t.CaptureMethod = Project.ImageryCaptureTask.CapturingMethods.AerialVideos
Root = SubFolderVideos
End Select
For Each i As Project.ImageryCaptureTask.FileProperties In t.FileCollection
Dim NewFilename As New FileInfo(Path.Combine(Root.FullName, i.LVItem.Text))
If NewFilename.Exists Then
' This should not happen, but if it does it gets handled here.
Else
Try
i.FI.MoveTo(NewFilename.FullName)
Catch IOEx As IOException
MsgBox(IOEx.Message & vbCr & vbCr & "Error renaming to " & NewFilename.FullName, vbOKOnly, IOEx.Source)
Catch Ex As Exception
MsgBox(Ex.Message)
End Try
End If
Next
Next
End If
Here is a photo showing the results from the last attempt. Of the 33 files, 7 of them failed to be renamed:
The goal here is to rename the image files created during our drone flights. These flights are static, same amount of images at the same GPS locations, so we want to be able to reference any existing flight images so we can extract the filenames. The only dynamic part of the filenames are the first 8 characters (Date: yyyymmDD).

It turns out that the issue is that some of the filenames are too long and could not be renamed.
To get passed the issue with filename lengths being longer than MAX_PATH I used the following threads:
Resolving filename longer than MAX_PATH Exceptions > Forum
Deal with filename longer than MAX_PATH > Forum ... [ specifically the answer by Wolf5 ]

Related

Writing large amounts of data to a csv file

I couldn't find anything specific to this so here goes.
I have a For Each loop where I want to write values to a csv file. Currently, I use a WriteToFile function:
Public Sub WriteToFile(stuff as string, morestuff as string, moremorestuff as string))
Dim strFile As String = "\\SomeServer\somefilepath\WriteTo.csv"
Try
If System.IO.File.Exists(strFile) = True Then
'rename with startdate and enddate. Always want to create new
Dim objWriter As New System.IO.StreamWriter(strFile, True)
objWriter.WriteLine(Stuff & "," & MoreStuff & "," & Moremorestuff)
objWriter.Close()
Else
Dim writeFile As IO.StreamWriter
writeFile = IO.File.CreateText(strFile)
writeFile.WriteLine("Stuff" & "," & "MoreStuff" & "," & "MoreMoreStuff")
writeFile.WriteLine(Stuff & "," & MoreStuff & "," & MoreMoreStuff)
writeFile.Close()
End If
Catch ex As Exception
MessageBox.Show("An error has occured in the WriteToFile subroutine: " & ex.ToString) ' & vbCrLf & strPlugin & vbCrLf & strVersion)
End Try
End Sub
Rather than closing the StreamWriter after every record is written, is there a way to keep it open? Or should it be kept open?
I made some changes and came up with this. However, using this code, how would I create a header in the csv file?
If cur.Count > 0 Then
Using writer As System.IO.StreamWriter = New IO.StreamWriter("C:\Temp\UWConditions.csv")
For Each lrdata As LoanReportData In cur
loan = session.Loans.Open(lrdata.Guid)
If Not IsNothing(loan) Then
For Each condition As UnderwritingCondition In loan.Log.UnderwritingConditions
Title = condition.Title.Replace(",", "")
Desc = condition.Description.Replace(",", "")
UWName = loan.Session.Users.GetUser(loan.Fields("UWID").Value).FullName.Replace(",", "")
writer.WriteLine(lrdata("Loan.LoanNumber") & "," & Title & "," & Desc & "," & UWName)
Next
loan.Close()
End If
Next
End Using
End If

WUApiLib.iupdate VB.net retrieving properties error

I have the following code to check windows updates
Function CheckWinUpdates() As Integer
CheckWinUpdates = 0
Dim WUSession As UpdateSession
Dim WUSearcher As UpdateSearcher
Dim WUSearchResults As ISearchResult
Try
WUSession = New UpdateSession
WUSearcher = WUSession.CreateUpdateSearcher()
WUSearchResults = WUSearcher.Search("IsInstalled=0 and Type='Software'")
CheckWinUpdates = WUSearchResults.Updates.Count
Catch ex As Exception
CheckWinUpdates = -1
End Try
If CheckWinUpdates > 0 Then
Try
'Dim Update As IUpdate
Dim i As Integer = 0
For i = 0 To WUSearchResults.Updates.Count - 1
'Update = WUSearchResults.Updates.Item(i)
EventLog.WriteEntry("Item is type: " & WUSearchResults.Updates.Item(i).ToString, EventLogEntryType.Information, 85)
EventLog.WriteEntry("Deadline: " & WUSearchResults.Updates.Item(i).Deadline.ToString, EventLogEntryType.Information, 85)
EventLog.WriteEntry("Type: " & WUSearchResults.Updates.Item(i).Type.ToString, EventLogEntryType.Information, 85)
EventLog.WriteEntry("Released on: " & WUSearchResults.Updates.Item(i).LastDeploymentChangeTime, EventLogEntryType.Information, 85)
EventLog.WriteEntry("This windows update is required: " & WUSearchResults.Updates.Item(i).Title, EventLogEntryType.Information, 85)
'EventLog.WriteEntry("This windows update is required: " & Update.Title & vbCrLf & "Released on: " &
' Update.LastDeploymentChangeTime & vbCrLf & "Type: " & Update.Type.ToString & vbCrLf &
' "Deadline: " & Update.Deadline.ToString & vbCrLf & vbCrLf & "Item is type: " & Update.ToString, EventLogEntryType.Information, 85)
Next
Catch ex As Exception
EventLog.WriteEntry("Error while attempting to log required updates:" & vbCrLf & ex.Message, EventLogEntryType.Error, 86)
End Try
End If
WUSearchResults = Nothing
WUSearcher = Nothing
WUSession = Nothing
End Function
My intention with this is to a) get the number of windows updates that are applicable, and b) to look at what other properties are available, and more specifically see how many are older than a week or 2.
I know that UpdateSearcher doesn't allow to search by date, so I am looking to iterate through each item and then later report on each one.
At the moment my function does quite happily return the number of updtes, but when I try to get any of the properties I get "Object reference not set to an instance of an object".
Any ideas where I'm going wrong?
I got this working, turns it it doesn't like the deadline property, I don't know it comes up with "object reference not set", but for what I need it doesn't matter.

URL monitor keeps increasing memory usage

I have written a URL monitoring program in vb using .net 4.0. Basically it sets a timer checks the url every 60 minutes using an htpwebreques/httpwebresponse and sends an email if the url is down. However the memory used by the application keeps increasing every time the url is checked. This will obviously eventually cause a problem as the app is designed to run permanently monitoring a website for availability and the monitoring machine will eventually run out of resources.
Code for my CheckURL routine below. Any advice greatly appreciated, thanks in advance.
Private Sub checkURL()
Timer1.Stop()
Dim wReq As HttpWebRequest
Dim wResp As HttpWebResponse ' WebResponse
wReq = HttpWebRequest.Create(url)
wReq.Method = "HEAD"
Try
wResp = wReq.GetResponse()
If wResp.StatusCode = 200 Then
txtResponse.Text = wResp.StatusCode & ": " & wResp.StatusDescription & vbNewLine & "The " & siteName & " is up"
'Only send success results if specified
If sendOnFailure = False Then
sendResults = True
End If
Else txtResponse.Text = "There may be a problem with the " & siteName & vbNewLine & "Please verify manually that it is operational." & vbNewLine & "The response received was:" & vbNewLine & "Status Code: " & wResp.StatusCode & " - " & wResp.StatusDescription
sendResults = True
End If
wResp.Close()
wResp = Nothing
wReq = Nothing
Catch ex As Exception
txtResponse.Text = "There may be a problem with the " & siteName & vbNewLine & "The error returned was:" & vbNewLine & ex.ToString
sendResults = True
End Try
txtLastCheck.Text = Now.ToString("d MMM yyyy HH:mm")
setNextCheck()
End Sub
First, you should use Option Strict On, which will show you where you have variable type mismatches and may even suggest corrections for you, for example, see where the DirectCast operator is used in the following code.
Second, HttpWebResponse has a .Dispose() method, so you should call that when you have finished using it, or, as Zaggler pointed out, you can use Using to ensure that unmanaged resources are cleaned up properly, thus removing the memory leak you are concerned with. Note that there may be other similar problems in the code we can't see.
You should not set things to Nothing in an attempt to get rid of them - doing so messes with the garbage collector and does nothing to ensure their clean disposal.
Option Strict On
' ....
Private Sub checkURL()
timer1.Stop()
Dim wReq As HttpWebRequest = DirectCast(HttpWebRequest.Create(url), HttpWebRequest)
wReq.Method = "HEAD"
Try
Using wResp As HttpWebResponse = DirectCast(wReq.GetResponse(), HttpWebResponse)
If wResp.StatusCode = 200 Then
txtResponse.Text = wResp.StatusCode & ": " & wResp.StatusDescription & vbNewLine & "The " & siteName & " is up"
'Only send success results if specified
If sendOnFailure = False Then
sendResults = True
End If
Else txtResponse.Text = "There may be a problem with the " & siteName & vbNewLine & "Please verify manually that it is operational." & vbNewLine & "The response received was:" & vbNewLine & "Status Code: " & wResp.StatusCode & " - " & wResp.StatusDescription
sendResults = True
End If
wResp.Close()
End Using
Catch ex As Exception
txtResponse.Text = "There may be a problem with the " & siteName & vbNewLine & "The error returned was:" & vbNewLine & ex.ToString
sendResults = True
End Try
txtLastCheck.Text = Now.ToString("d MMM yyyy HH:mm")
setNextCheck()
End Sub

MSXML2.DOMDocument load function fails in VBA

I've been struggling with the below issue for a while now and couldn't find the solution yet.
There is an iShare page with an XML file that I want to download using VBA code, then later process the XML file and save into MS Access database.
I've been using the below code for about 4 years now, it worked perfectly without any issues. But suddenly it stopped working this week.
Any ideas why?
the code:
Private Function GetRequests() As Boolean
On Error GoTo ErrHandler
Dim oDoc As MSXML2.DOMDocument
Dim Url As String
Dim sFileName As String
Set oDoc = New MSXML2.DOMDocument
oDoc.async = False
Url = cUrlDatabase & "/" & cApplicationName & "/In/" & cReqXmlFile
UpdateStatus "Loading " & cReqXmlFile
If Not oDoc.Load(Url) Then
c_sLastError = "Could not load XML " & Url
GoTo EndProc
End If
sFileName = sPath & "\Data\requests.xml"
oDoc.Save sFileName
GetRequests = True
End Function
The code fails at the oDoc.Load(Url) part, it comes back false.
Here's an example of how to gather error details:
Dim xDoc As MSXML.DOMDocument
Set xDoc = New MSXML.DOMDocument
If xDoc.Load("C:\My Documents\cds.xml") Then
' The document loaded successfully.
' Now do something intersting.
Else
' The document failed to load.
Dim strErrText As String
Dim xPE As MSXML.IXMLDOMParseError
' Obtain the ParseError object
Set xPE = xDoc.parseError
With xPE
strErrText = "Your XML Document failed to load" & _
"due the following error." & vbCrLf & _
"Error #: " & .errorCode & ": " & xPE.reason & _
"Line #: " & .Line & vbCrLf & _
"Line Position: " & .linepos & vbCrLf & _
"Position In File: " & .filepos & vbCrLf & _
"Source Text: " & .srcText & vbCrLf & _
"Document URL: " & .url
End With
MsgBox strErrText, vbExclamation End If
Set xPE = Nothing
End If
Example taken from here.
For other people finding this post:
The xml parser by now has implemented different error types (see here).
You would have to use the following code
Set objXML = CreateObject("Msxml2.DOMDocument.6.0")
ObjXML.async=true
objXML.load "/path/to/xml"
If objXML.parseError.errorCode <> 0 Then
MsgBox "Error was " + objXML.parseError.reason
End If
This should help you debug your .xml file.
For anyone else struggling with this, I found this error to be caused by text encoded in a format which could not be parsed in VBA (some weird E symbol). The objXML was nothing after the .load. I'm sure there are many possible causes, but I'll share what I found in case this helps someone. Thanks to the guys above for the error handling routines.

VB.net Delete a file which keeps getting replaced

I have written a VB.net executable that deletes a file then transfers a different one in it's place. An extract of the code is shown below. The problem is it fails every time due to the program that uses the file recreates it immediately after deletion.
How can I delete the file and prevent it being replaced? I cannot change anything about the program that's recreating it.
If IO.File.Exists(AMPDir & "AMP_DIR.DAT") = False Then
MsgBox("The following file is missing..." & vbCrLf & vbCrLf & " " & "AMP_DIR.DAT", MsgBoxStyle.Critical, "Error...")
Me.Close()
End
ElseIf IO.File.Exists(AMPDir & "AMP_DIR.DAT") = True And IO.File.Exists(LOGDir & "LOGIC.INF") = True Then
System.IO.File.Delete(AMPDir & "AMP_DIR.DAT")
System.IO.File.Copy(Path.GetDirectoryName(ConfigFile) & "\" & "AMP_DIR.DAT.IND", AMPDir & "AMP_DIR.DAT")
System.IO.File.SetAttributes(AMPDir & "AMP_DIR.DAT", FileAttributes.Normal)
End If