test if a folder exist or not in google drive - vb.net

I want to know if folder (subfolder) exist in google drive or not , after searching in this page , i try to do it , i create a boolean function which return true if folder exist .
here is a code of boolean function
Public Function exist(v As String) As Boolean
Dim pag As String
Dim req = Service.Files.List()
req.Q = "application/vnd.google-apps.folder"
req.PageToken = pag
Dim result = req.Execute()
If (result.NextPageToken IsNot Nothing) Then
Return False
Else
Return True
End If
End Function
and here how i call it
If (exist(dat_sauv.SelectedItem) = False) Then
MessageBox.Show("folder exist")
End If
the exception is
exception has declenched in exist method in this insctruction
Dim result = req.Execute()
is my method correct or not ? can you help me

There are two problems with your code.
Improper query
Your line req.Q = "application/vnd.google-apps.folder"
should be
req.Q = "mimeType='application/vnd.google-apps.folder' and name = '"+v+"' and trashed=false"
You'll probably need to tidy up the quoting and escaping (ie Don't copy/paste and expect it to work first time)
use of nextPageToken
The presence of the folder will not be indicated by the presence of nextpageToken. Instead, you need to check the files array within the response for >0 elements.

Related

For Each loop doesn't break with Try Catch in VB.NET

I am writing a simple application that copies files recursively from one directory to another. The application has a checkbox where the user can choose to overwrite the destination files if they exist. If the file exists, and overwrite is deselected, then the catch statement should exit the function and return 1, so that the main code can handle the error.
Dim result As Integer
Dim sourceDirectoryInfo As New System.IO.DirectoryInfo(sourcePathHere)
' If the destination folder doesn't exist then create it
If Not System.IO.Directory.Exists(destinationPathHere) Then
System.IO.Directory.CreateDirectory(destinationPathHere)
End If
Dim overwriteHere As Boolean
If chkOverwrite.Checked = True Then
overwriteHere = True
Else
overwriteHere = False
End If
Dim fileSystemInfo As System.IO.FileSystemInfo
Try
For Each fileSystemInfo In sourceDirectoryInfo.GetFileSystemInfos
Dim destinationFileName As String =
System.IO.Path.Combine(destinationPathHere, 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, overwriteHere)
Else
' Recursively call the mothod to copy all the nested folders
CopyDirectory(fileSystemInfo.FullName, destinationFileName)
End If
Next
result = 0
Catch
txtStatus.Text = "Error"
result = 1
End Try
'MsgBox(result) <=For Testing
Return result
End Function
I would expect that since the catch is outside the for Each loop, once the catch is hit it should set result to 1 and return from the function. However, when putting a MsgBox there, I'm seeing the box appear 9 times as follows:
1,1,1,0,1,1,0,0
These results don't seem to correspond to my source files at all.
Since the last result is returning 0, the main code completes as if there was no error. Why isn't my code breaking out of the For Each loop (or maybe something else is happening here)?
There are no other loops in the code calling the function, it is called as follows:
Dim success As Integer = CopyDirectory(sourcePath, destinationPath)
Thanks Chris Dunaway, the problem was that the function is recursive, so when the Return is called, it just goes up one level of the function but continues. I fixed that by creating an error flag, that once set to true, will persist throughout all the iterations of the function so that it exits gracefully from all of them:
Public Function CopyDirectory(ByVal sourcePathHere As String, ByVal destinationPathHere As String, Optional overwriteFiles As Boolean = False, Optional errFlag As Boolean = False) As Boolean
Dim sourceDirectoryInfo As New System.IO.DirectoryInfo(sourcePathHere)
' If the destination folder doesn't exist then create it
If Not System.IO.Directory.Exists(destinationPathHere) Then
System.IO.Directory.CreateDirectory(destinationPathHere)
End If
Dim fileSystemInfo As System.IO.FileSystemInfo
Try
For Each fileSystemInfo In sourceDirectoryInfo.GetFileSystemInfos
Dim destinationFileName As String =
System.IO.Path.Combine(destinationPathHere, 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, overwriteFiles)
Else
' recursive call of the function, accepting the return with the errFlag will stop the function from running again.
errFlag = CopyDirectory(fileSystemInfo.FullName, destinationFileName, overwriteFiles, errFlag)
End If
Next
Catch
txtStatus.Text = "Error"
errFlag = True
End Try
Return errFlag
End Function

Check if a file is a valid SQLite database

I need to check whether a file (with unknown extension) is a valid SQLite database.
My function works fine, but when it fails, the file is still locked after exiting the function:
Public Function IsSqliteDB(ByVal uPath As String) As Boolean
'Workaround for my problem: Make a copy and work on this because this function is going to lock the file unfortunately
Dim sNewPath As String
sNewPath = Settings.Locations.Folder_LocalAppData_Temp & "\temp_" & Replace(Now.ToString, ":", "_") & ".db"
modIO.FileForceCopy(uPath, sNewPath)
Dim bIsSQLiteDB As Boolean = False
Dim c As New dhRichClient3.cConnection
Dim r As dhRichClient3.cRecordset
Try
Dim b As Boolean = c.OpenDB(sNewPath) 'returns true although this is not an sqlite-db. Can't do anything about it
R = c.OpenRecordset("SELECT * FROM sqlite_master")
bIsSQLiteDB = True
Catch ex As Exception
r = Nothing
c = Nothing
Finally
r = Nothing
c = Nothing
End Try
modIO.DeleteFile(sNewPath)'this fails. File is locked
Return bIsSQLiteDB
End Function
Does anybody see where I could ensure that the file is not locked anymore? Or do I really have to work with a copy of the file because the behaviour of the COM component is not really known (closed source unfortunately)?
I could indeed work with a backup, but the file may be really large (> 1 GB), so I would like to avoid making a copy to work on if I could avoid it.
There is no "close" function in dhRichClient. "Close" is called internally once the cConection goes out out scope, I guess. Calling GC.Collect() at the end of the function does not help.
To determine if a file is an SQLite database, just check the first 16 bytes of the database header.
from tmighty's comment:
Public Function IsSqliteDB(ByVal uPath As String) As Boolean
Dim bytes(16) As Byte
Using fs As New IO.FileStream(uPath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)
fs.Read(bytes, 0, 16)
End Using
Dim text As String = System.Text.ASCIIEncoding.ASCII.GetString(bytes)
Return text.Contains("SQLite format")
End Function

Why won't my variable set to an instance of an object?

The program is a booking system (amongst other things) for a holiday letting company. I am working on the screen where you can see properties and ammend them or add more (etc)
Okay so It works fine in my other cases, but this one it just doesn't want to accept...I expect it's something stupid. Basically In the initial loading of the entire program I filled the Data Tables with the relevant info and then accessed them when needs be, in this case I am in the Form Properties and want to access Bookings (Which were made in FrmBookings) to see when the property is next booked to have guests in.
Dim Intcounter As Integer = 0
Dim NumberBookingRecords As Integer = BookingsNumRecs
Dim PropertyName As String
Dim PropertyFromBookings As String
Do
PropertyName = DTProperties(Intcounter)("Property Name").ToString
PropertyFromBookings = (DTBookings(NumberBookingRecords)("Property").ToString)
If PropertyName = PropertyFromBookings Then
lblDateOfArrival.Text = (DTBookings(NumberBookingRecords)("Arrival").ToString)
Intcounter = Intcounter + 1
Else
If Not NumberBookingRecords = 0 Then
NumberBookingRecords = NumberBookingRecords - 1
Else
End If
End If
Loop Until Intcounter >= intNumPropertyRecs
However when I get to PropertyFromBookings = (DTBookings(NumberBookingRecords)("Property").ToString)
it tells me that it could not be set to an instance of an object...no matter what I try an access from DTBookings I get the same response.
This is in the initial load form at the opening of the program
Dim FSBookings As New FileStream(strFileNameBookings, FileMode.OpenOrCreate, FileAccess.Read)
Application.DoEvents()
If FileLen(strFileNameBookings) > 0 Then
DTBookings.ReadXmlSchema(strFileNameBookings)
DTBookings.ReadXml(strFileNameBookings)
BookingsNumRecs = DTBookings.Rows.Count
intCurrRec = 1
Else
End If
FSBookings.Close()
blnStopAuto = True
blnStopAuto = False
Based on your code sample, DTBookings() is a function call. There are two possibilties here. Either:
The result of that function is Nothing, and when you try to use a Nothing as if there were an actual object there, (in this case, when trying to look up the ("Property") indexer) you'll get that exception, or ...
The result of the ("Property") index returns Nothing, in which case you'll get that exception when you try to call the .ToString() method.

Searching obsolute occurrence of a string in a file in VB.net

I need to find obsolute occurrence of a string in a file.
If a string "I_LOVE_INDIA" in a file.
If the input string is "I_LOVE" then search status should be false.
If the input string is "I_LOVE_INDIA" then search status should be true.
I am not able to get using below one:
System.IO.File.ReadAllText("D:\asdf\def.txt").IndexOf("string_to_search")
This will work:
System.IO.File.ReadAllText("D:\asdf\def.txt").IndexOf("I_LOVE_INDIA")
If you want it to fail when you look for "I_LOVE_INDIA_TOO" then you'll need to check for that, eg:
Dim s as String = System.IO.File.ReadAllText("D:\asdf\def.txt")
Dim success as Boolean = CheckStringContainsILoveIndia(s)
Public Function CheckStringContainsILoveIndia(Byval s as String) as Boolean
Dim success as Boolean = False
If s.IndexOf("I_LOVE_INDIA_TOO") == -1 AND s.IndexOf("I_LOVE_INDIA") > -1 Then
success = True
End If
return success
End Sub

How can I check if filename contains a portion of a string in vb.net

I have a userform in 2008 vb express edition. A part number is created from user input via a concat string. I want to then check if a certain portion of the part number exists in the existing file names in a directory. Below is a more detailed explanation.
This is my code for creating a part number from the user input on the form.
L_PartNo.Text = String.Concat(CB_Type.Text, CB_Face.Text, "(", T_Width.Text, "x", T_Height.Text, ")", mount, T_Qty.Text, weep, serv)
I then have the following code to tell the user if the configuration (part no) they just created exists
L_Found.Visible = True
If File.Exists("Z:\Cut Sheets\TCS Products\BLANK OUT SIGN\" & (L_PartNo.Text) & ".pdf") Then
L_Found.Text = "This configuration exists"
Else
L_Found.Text = "This configuration does NOT exist"
End If
This is where I need help. The part no will look like this BX002(30x30)A1SS I want to compare 002(30x30) (just this part of the file name) to all the files in one directory. I want a yes or no answer to the existance and not a list of all matching files. The code below is everything I've tried, not all at the same time.
Dim b As Boolean
b = L_PartNo.Text.Contains(NewFace)
Dim NewFace As String = String.Concat(CB_Face.Text, "(", T_Width.Text, "x", T_Height.Text, ")")
Dim NewFace = L_PartNo.Text.Substring(2, 10)
If filename.Contains(NewFace) Then
lNewFace.Visible = False
Else
lNewFace.Visible = True
End If
The code below was a translation from the answer in C# but it does not work either
Dim contains As Boolean = Directory.EnumerateFiles(path).Any(Function(f) [String].Equals(f, "myfilethree", StringComparison.OrdinalIgnoreCase))
Here's an example of how you can do it without the fancy LINQ and Lambda which seem to be confusing you:
Public Function FileMatches(folderPath As String, filePattern As String, phrase As String) As Boolean
For Each fileName As String In Directory.GetFiles(folderPath, filePattern)
If fileName.Contains(phrase) Then
Return True
End If
Next
Return False
End Function
Or, if you need it to be case insensitive:
Public Function FileMatches(folderPath As String, filePattern As String, phrase As String) As Boolean
For Each fileName As String In Directory.GetFiles(folderPath, filePattern)
If fileName.ToLower().Contains(phrase.ToLower()) Then
Return True
End If
Next
Return False
End Function
You would call the method like this:
lNewFace.Visible = FileMatches(path, "*.pdf", NewFace)
Try this:
lNewFace.Visible = IO.Directory.GetFiles(path, "*.pdf").Where(Function(file) file. _
Substring(2, 10) = NewFace).FirstOrDefault Is Nothing
Consider that the substring function will throw an exception if its arguments exceed the length of the string it is parsing