Handle exceptions in VB.NET SSIS script with WebClient (FTP download) - vb.net

In SSIS I am using a VB.NET script task to download a file from an FTP folder.
The script is the following
Imports System
Imports System.Data
Imports Microsoft.SqlServer.Dts.Runtime
Imports System.Net
Public Class ScriptMain
Public Sub Main()
Dim objWebClient As WebClient = New WebClient()
Dim strDownloadURL As String = "ftp://mydownloadhosting.com/myfolder/" + Dts.Variables("GetDate").Value.ToString() + "_daily.xml"
Dim strFileName As String = Dts.Variables("WorkingFile").Value.ToString()
Dim wp As WebProxy = New WebProxy("my.proxy.local", 1234)
objWebClient.Proxy = wp
objWebClient.Credentials = New System.Net.NetworkCredential("username", "password")
objWebClient.DownloadFile(strDownloadURL, strFileName)
Dts.TaskResult = Dts.Results.Success
End Sub
End Class
it works correctly but my target is to manage the exception, in particular to discriminate between:
file not found
all other problems (timeout, problem with proxy, ...)
I have made some research about how to manage exception with WebClient() and I have found these:
How to catch 404 WebException for WebClient.DownloadFileAsync
How do I check a WebClient Request for a 404 error
Handling two WebException's properly
which they give different forms of the following:
try
{
// try to download file here
}
catch (WebException ex)
{
if (ex.Status == WebExceptionStatus.ProtocolError)
{
if (((HttpWebResponse)ex.Response).StatusCode == HttpStatusCode.NotFound)
{
// handle the 404 here
}
}
else if (ex.Status == WebExceptionStatus.NameResolutionFailure)
{
// handle name resolution failure
}
}
The main problem is that my code is in VB.NET and all the posted answered are written in C#, how can make a try/catch construct to handle an exception in my code?

An equivalent code in VB.NET is:
Try
' try to download file here
Catch ex As WebException
If ex.Status = WebExceptionStatus.ProtocolError Then
If DirectCast(ex.Response, HttpWebResponse).StatusCode = HttpStatusCode.NotFound Then
' // handle the 404 here
End If
ElseIf ex.Status = WebExceptionStatus.NameResolutionFailure Then
' handle name resolution failure
End If
End Try
Though the above/your code is for HTTP, not for FTP. FTP has different status codes.
For FTP, use:
FtpWebResponse and
FtpStatusCode.
For some FTP examples, see:
C#: How to check if file exists on FTP before FtpWebRequest
VB.NET: VB.net - see if remote file exists

There are many C# to VB.NET converters that you can refer to when you need to convert simple codes:
Telerik C#/VB.NET online code converter
Instant VB – Our C# to VB.NET Converter
The equivalent VB.NET code is:
Imports System
Imports System.Data
Imports Microsoft.SqlServer.Dts.Runtime
Imports System.Net
Public Class ScriptMain
Public Sub Main()
Try
Dim objWebClient As WebClient = New WebClient()
Dim strDownloadURL As String = "ftp://mydownloadhosting.com/myfolder/" + Dts.Variables("GetDate").Value.ToString() + "_daily.xml"
Dim strFileName As String = Dts.Variables("WorkingFile").Value.ToString()
Dim wp As WebProxy = New WebProxy("my.proxy.local", 1234)
objWebClient.Proxy = wp
objWebClient.Credentials = New System.Net.NetworkCredential("username", "password")
objWebClient.DownloadFile(strDownloadURL, strFileName)
Dts.TaskResult = Dts.Results.Success
Catch ex As WebException
If ex.Status = WebExceptionStatus.ProtocolError Then
If (CType(ex.Response, HttpWebResponse)).StatusCode = HttpStatusCode.NotFound Then
'handle the 404 here
End If
ElseIf ex.Status = WebExceptionStatus.NameResolutionFailure Then
'handle name resolution failure
End If
Dts.TaskResult = Dts.Results.Failure
End Try
End Sub
End Class

Related

Create an object in VB.Net to use in VBA

Firstly, I'm quite new to this so be gentle!
I am trying to create a class/object in VB.net for use in vba. I have used Gary Whitcher's code from the bottom of this post:
Sample vb.net code to upload file to Amazon S3 storage
I have created a class in Visual Studio and managed to get it to output a TLB file which i can import to VBA in Excel.
I can then use the object in VBA to create a new folder in the S3 storage system however I am running into problems when using the 'AddFileToFolder' method.
I have had to edit Gary's code a little to get it to compile in VS, the edited version is below.
Imports Amazon.S3
Imports Amazon.S3.Model
Imports Amazon
Imports Amazon.S3.Util
Imports System.Collections.ObjectModel
Imports System.IO
Public Class aws_s3
Const AWS_ACCESS_KEY As String = "AccessKey" 'is set to MY actual key
Const AWS_SECRET_KEY As String = "SecretKey" 'is set to MY actual key
Private Property s3Client As IAmazonS3
Sub New()
Try
s3Client = New AmazonS3Client(AWS_ACCESS_KEY, AWS_SECRET_KEY, RegionEndpoint.USEast1)
Catch ex As Exception
End Try
End Sub
Public Function CreateFolder(bucketName As String, folderName() As String) As String
Dim returnval As String = ""
Try
Try
Dim folderKey As String = ""
If Not AmazonS3Util.DoesS3BucketExist(s3Client, bucketName) Then
returnval = "Bucket does not exist"
Else
For i = 0 To folderName.Length - 1
folderKey += folderName(i) & "/"
Next
' folderKey = folderKey & "/" 'end the folder name with "/"
Dim request As PutObjectRequest = New PutObjectRequest()
request.BucketName = bucketName
request.StorageClass = S3StorageClass.Standard
request.ServerSideEncryptionMethod = ServerSideEncryptionMethod.None
' request.CannedACL = S3CannedACL.BucketOwnerFullControl
request.Key = folderKey
request.ContentBody = String.Empty
s3Client.PutObject(request)
End If
Catch ex As Exception
returnval = ex.Message
End Try
Catch ex As AmazonS3Exception
returnval = ex.Message
End Try
Return returnval
End Function
Public Function AddFileToFolder(FileName As String, bucketName As String, folderName As String) As String
Dim returnval As String = ""
Try
Try
If Not AmazonS3Util.DoesS3BucketExist(s3Client, bucketName) Then
Dim fname() As String = folderName.Split("/")
CreateFolder(bucketName, fname)
Else
Dim path As String = FileName
Dim file As FileInfo = New FileInfo(path)
Dim key As String = String.Format("{0}/{1}", folderName, file.Name)
Dim por As PutObjectRequest = New PutObjectRequest()
por.BucketName = bucketName
por.StorageClass = S3StorageClass.Standard
por.ServerSideEncryptionMethod = ServerSideEncryptionMethod.None
por.CannedACL = S3CannedACL.PublicRead
por.Key = key
por.InputStream = file.OpenRead()
s3Client.PutObject(por)
End If
Catch ex As Exception
returnval = ex.Message
End Try
Catch ex As AmazonS3Exception
returnval = ex.Message
End Try
Return returnval & " dll"
End Function
End Class
Using VBA, I have created the above object and can successfully execute CreateFolder but when executing addfiletofolder i get the error "Class does not support automation or does not support expected interface"
the VBA code looks like this:
Dim aws As AWS_S3
Dim Result As String
Dim UploadFile As String
UploadFile = "C:\Zipped Builds\Hinchley Legion.zip"
Set aws = New AWS_S3
Dim fld(1) As String
fld(0) = "folder"
fld(1) = "subfolder"
Result = aws.CreateFolder("nsmcustomercontent", fld)
If Result <> "" Then GoTo errHandle
Result = aws.AddFileToFolder(UploadFile, "nsmcustomercontent", fld)
If Result <> "" Then GoTo errHandle
Exit Sub
errHandle:
MsgBox Result
End Sub
I'm guessing from the fact that CreateFolder works fine but AddFileToFolder doesn't, there is a problem in the class as created in VS, missing a dependancy or something?
Thanks Anu6is, that was indeed the problem. The author of the class had wrote the following for usage which had thrown me off:
ADD FILE TO FOLDER
Dim fld(1) As String
fld(0) = <foldername>
fld(1) = <subfoldername>
'List each sub folder as an element in array
Dim rtrn As String = aws.AddFileToFolder(<local file name>,<bucketname>, fld)
I need to get better at reading VB.Net i think! Many thanks for your quick reply, much appreciated.

Mutex not locking and using not releasing file handle

I am having problems getting a file handle to close properly. I have tried to use an additional Mutex to ensure only one thread has access to this file at a time.
As far as I understand it the Using construct should ensure that the file handle is released properly, and the Mutex should ensure that this code can only run in 1 thread at a time.
The error occurs when the logger is called multiple times in rapid succession.
The gethashcode was an attempt to verify that the mutex instance is the same.
Error Message:
An unhandled exception of type 'System.IO.IOException' occurred in mscorlib.dll
The process cannot access the file '****\LOG.log' because it is being used by another process.
Source:
Imports System.IO
Imports System.Net.Mail
Imports System.Threading
Public NotInheritable Class FileLogger
Private Shared ReadOnly _instance As New Lazy(Of FileLogger)(Function() New FileLogger(), System.Threading.LazyThreadSafetyMode.ExecutionAndPublication)
Public LOG_LEVEL As Integer = 4
Public LEVELS As New Dictionary(Of Double, String)
Private Shared strFile As String = "LOG.log"
Public Shared FileLoc As New Mutex()
Public Shared ReadOnly Property getLogger() As FileLogger
Get
Return _instance.Value
End Get
End Property
Private Sub New()
Dim strFile As String = "yourfile.log"
LEVELS.Add(0, "FATAL ")
LEVELS.Add(1, "CRITICAL")
LEVELS.Add(2, "ERROR ")
LEVELS.Add(3, "INFO ")
LEVELS.Add(4, "DEBUG ")
LEVELS.Add(2.5, "WARNING ")
End Sub
Public Sub writeEntry(ByVal message As String, ByVal level As Double)
If level <= LOG_LEVEL Then
Dim log_str As String = String.Format("{0} - in: {3} - {1}: {2}", DateTime.Now.ToString, LEVELS(level), message, Thread.CurrentThread.ManagedThreadId)
Console.WriteLine(log_str)
If level < 3 Then ' warning or greater write to file else just console
Console.WriteLine(FileLoc.GetHashCode())
FileLoc.WaitOne(Timeout.Infinite)
Using sw As StreamWriter = New StreamWriter(strFile, True) '<-- Debugger points to this line
sw.WriteLine(log_str)
End Using
FileLoc.ReleaseMutex()
End If
If level <= 2 Then 'if error or greater send email
FileLoc.WaitOne(Timeout.Infinite)
Dim mail As New MailMessage
mail.To.Add("email")
mail.From = New MailAddress("email")
mail.Subject = "Error on MC Server (SERVERNAME)"
mail.Body = log_str
mail.IsBodyHtml = True
mail.Attachments.Add(New Attachment(strFile))
Dim smtp As New SmtpClient
smtp.Host = "IPADDR"
smtp.Send(mail)
FileLoc.ReleaseMutex()
End If
End If
End Sub
End Class
The email section was not closing the file correctly. wrapping this in a using construct fixed the issue.
I also ended up implementing the SyncLock construct around the entire operation.
as some of the comments have pointed out the mutex may or may not have been doing what it was supposed to, but the file handle was still open from the attachment operation.
Public Sub writeEntry(ByVal message As String, ByVal level As Double)
SyncLock FileLoc
If level <= LOG_LEVEL Then
Dim log_str As String = String.Format("{0} - in: {3} - {1}: {2}", DateTime.Now.ToString, LEVELS(level), message, Thread.CurrentThread.ManagedThreadId)
Console.WriteLine(log_str)
If level < 3 Then ' warning or greater write to file else just console
Console.WriteLine(FileLoc.GetHashCode())
Using sw As StreamWriter = New StreamWriter(strFile, True)
sw.WriteLine(log_str)
End Using
End If
If level <= 2 Then 'if error or greater send email
Using at As Attachment = New Attachment(strFile)
Dim mail As New MailMessage
mail.To.Add("email")
mail.From = New MailAddress("email")
mail.Subject = "Error on MC Server (servername)"
mail.Body = log_str
mail.IsBodyHtml = True
mail.Attachments.Add(at)
Dim smtp As New SmtpClient
smtp.Host = "IPADDR"
smtp.Send(mail)
End Using
End If
End If
End SyncLock
End Sub

How to modify existing REST web service to work with SSL

I have the following simple REST service running based on the code found on MSDN - code below.
How can I modify this to be able to use transport security - SSL ?
I've been googling around for a solution, but it seems that most examples are mentioning to modify web.config file, but this example doesn't even have that... Thanks for any help with this one!
Imports System
Imports System.Collections.Generic
Imports System.ServiceModel
Imports System.ServiceModel.Description
Imports System.ServiceModel.Web
Imports System.Text
<ServiceContract()> _
Public Interface IService
<OperationContract()> _
<WebGet()> _
Function EchoWithGet(ByVal s As String) As String
<OperationContract()> _
<WebInvoke()> _
Function EchoWithPost(ByVal s As String) As String
end interface
Public Class Service
Implements IService
Public Function EchoWithGet(ByVal s As String) As String Implements IService.EchoWithGet
Return "You said " + s
End Function
Public Function EchoWithPost(ByVal s As String) As String Implements IService.EchoWithPost
Return "You said " + s
End Function
End Class
Module program
Sub Main()
Dim host As WebServiceHost = New WebServiceHost(GetType(Service), New Uri("http://localhost:8000/"))
Try
Dim ep As ServiceEndpoint = host.AddServiceEndpoint(GetType(IService), New WebHttpBinding(), "")
host.Open()
Using cf As New ChannelFactory(Of IService)(New WebHttpBinding(), "http://localhost:8000")
cf.Endpoint.Behaviors.Add(New WebHttpBehavior())
Dim channel As IService = cf.CreateChannel()
Dim s As String
Console.WriteLine("Calling EchoWithGet via HTTP GET: ")
s = channel.EchoWithGet("Hello, world")
Console.WriteLine(" Output: {0}", s)
Console.WriteLine("")
Console.WriteLine("This can also be accomplished by navigating to")
Console.WriteLine("http://localhost:8000/EchoWithGet?s=Hello, world!")
Console.WriteLine("in a web browser while this sample is running.")
Console.WriteLine("")
Console.WriteLine("Calling EchoWithPost via HTTP POST: ")
s = channel.EchoWithPost("Hello, world")
Console.WriteLine(" Output: {0}", s)
Console.WriteLine("")
End Using
Console.WriteLine("Press <ENTER> to terminate")
Console.ReadLine()
host.Close()
Catch cex As CommunicationException
Console.WriteLine("An exception occurred: {0}", cex.Message)
host.Abort()
End Try
End Sub
End Module
Adding the following solved my problem and all traffic goes through HTTPS. I hope this will help someone in the future.
Dim binding As New WebHttpBinding
binding.Security.Mode = WebHttpSecurityMode.Transport
Dim store As New X509Store(StoreName.My, StoreLocation.LocalMachine)
store.Open(OpenFlags.ReadWrite)
Dim cert = store.Certificates.Find(X509FindType.FindBySubjectName, "localhost", False)(0)
store.Close()
Dim bindPortToCertificate As New Process
bindPortToCertificate.StartInfo.FileName = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.SystemX86), "netsh.exe")
bindPortToCertificate.StartInfo.Arguments = String.Format("http add sslcert ipport=0.0.0.0:{0} certhash={1} appid={{{2}}}", 22370, cert.Thumbprint, Guid.NewGuid())
bindPortToCertificate.Start()
bindPortToCertificate.WaitForExit()

Importing Google Drive Quickstart Code to Visual Basic

I am trying to get the Quickstart code for .Net imported to Visual Basic (VB .NET) and I had some errors. I am a newbie to this kind of programming. Would appreciate some pointers, or someone pointing out something that is fundamentally wrong with the code.
Appreciate the help!
The errors that I get when I try to compile the Console App are:
Error 2 Argument not specified for parameter 'arg' of 'Private Shared Function GetAuthorization(arg As Google.Apis.Authentication.OAuth2.DotNetOpenAuth.NativeApplicationClient) As DotNetOpenAuth.OAuth2.IAuthorizationState'. C:\Documents and Settings\Hirak\Local Settings\Application Data\Temporary Projects\Nipod Drive Console\Module1.vb 22 86 Nipod Drive Console
Error 3 'BaseClientService' is ambiguous in the namespace 'Google.Apis.Services'. C:\Documents and Settings\Hirak\Local Settings\Application Data\Temporary Projects\Nipod Drive Console\Module1.vb 23 48 Nipod Drive Console
Imports System
Imports System.Diagnostics
Imports DotNetOpenAuth.OAuth2
Imports Google.Apis.Authentication.OAuth2
Imports Google.Apis.Authentication.OAuth2.DotNetOpenAuth
Imports Google.Apis.Drive.v2
Imports Google.Apis.Drive.v2.Data
Imports Google.Apis.Util
Imports Google.Apis.Services
Namespace GoogleDriveSamples
Class DriveCommandLineSample
Shared Sub Main(ByVal args As String)
Dim CLIENT_ID As [String] = "YOUR_CLIENT_ID"
Dim CLIENT_SECRET As [String] = "YOUR_CLIENT_SECRET"
'' Register the authenticator and create the service
Dim provider = New NativeApplicationClient(GoogleAuthenticationServer.Description, CLIENT_ID, CLIENT_SECRET)
Dim auth = New OAuth2Authenticator(Of NativeApplicationClient)(provider, GetAuthorization)
Dim service = New DriveService(New BaseClientService.Initializer() With { _
.Authenticator = auth _
})
Dim body As New File()
body.Title = "My document"
body.Description = "A test document"
body.MimeType = "text/plain"
Dim byteArray As Byte() = System.IO.File.ReadAllBytes("document.txt")
Dim stream As New System.IO.MemoryStream(byteArray)
Dim request As FilesResource.InsertMediaUpload = service.Files.Insert(body, stream, "text/plain")
request.Upload()
Dim file As File = request.ResponseBody
Console.WriteLine("File id: " + file.Id)
Console.WriteLine("Press Enter to end this process.")
Console.ReadLine()
End Sub
Private Shared Function GetAuthorization(ByVal arg As NativeApplicationClient) As IAuthorizationState
' Get the auth URL:
Dim state As IAuthorizationState = New AuthorizationState( New () {DriveService.Scopes.Drive.GetStringValue()})
state.Callback = New Uri(NativeApplicationClient.OutOfBandCallbackUrl)
Dim authUri As Uri = arg.RequestUserAuthorization(state)
' Request authorization from the user (by opening a browser window):
Process.Start(authUri.ToString())
Console.Write(" Authorization Code: ")
Dim authCode As String = Console.ReadLine()
Console.WriteLine()
' Retrieve the access token by using the authorization code:
Return arg.ProcessUserAuthorization(authCode, state)
End Function
End Class
End Namespace
I reliase this is an old subject, but this may help someone in future, make sure you compile in framework 3.5
Sorry cant seem to edit or delete my previous answer, for anyone in future, this should help:
Imports System
Imports System.Diagnostics
Imports DotNetOpenAuth.OAuth2
Imports Google.Apis.Authentication.OAuth2
Imports Google.Apis.Authentication.OAuth2.DotNetOpenAuth
Imports Google.Apis.Drive.v2
Imports Google.Apis.Drive.v2.Data
Imports Google.Apis.Util
Imports System.Security
Imports Google.Apis.Services
Public Class GoogleDrive
Public Function UploadFile() As Boolean
Const CLIENT_ID As String = "xxxxxxxxxxxxx.apps.googleusercontent.com"
Const CLIENT_SECRET As String = "-yyyyyyyyyyyyyyyyyyyyyyy"
'Register the authenticator and create the service
Dim provider As NativeApplicationClient = New NativeApplicationClient(GoogleAuthenticationServer.Description, CLIENT_ID, CLIENT_SECRET)
Dim getAuth As Func(Of NativeApplicationClient, IAuthorizationState) = AddressOf GetAuthorization
Dim auth As OAuth2Authenticator(Of NativeApplicationClient) = New OAuth2Authenticator(Of NativeApplicationClient)(provider, getAuth)
Dim service = New DriveService(New BaseClientService.Initializer() With {.Authenticator = auth})
Dim body As File = New File()
body.Title = "My document"
body.Description = "A test document"
body.MimeType = "text/plain"
Dim byteArray As Byte() = System.IO.File.ReadAllBytes("D:\document.txt")
Dim stream As System.IO.MemoryStream = New System.IO.MemoryStream(byteArray)
Dim request As FilesResource.InsertMediaUpload = service.Files.Insert(body, stream, "text/plain")
request.Upload()
Dim file As File = request.ResponseBody
MessageBox.Show("File : " & file.Id)
End Function
Private Function GetAuthorization(ByVal Client As NativeApplicationClient) As IAuthorizationState
Dim RetVal As IAuthorizationState
Dim state As IAuthorizationState = New AuthorizationState(New String() {DriveService.Scopes.Drive.GetStringValue()})
'Check to see if we have a saved refresh token
If My.Settings.SavedAuth.ToString <> "" Then
state.RefreshToken = My.Settings.SavedAuth
If (Client.RefreshToken(state)) Then
Return state
End If
End If
'Get the auth URL:
state.Callback = New Uri(NativeApplicationClient.OutOfBandCallbackUrl)
Dim authUri As Uri = Client.RequestUserAuthorization(state)
'Request authorization from the user (by opening a browser window):
Process.Start(authUri.ToString())
'wait until user has entered the code
Dim authCode As String = InputBox("Authorisation code", "Authorisation Code", "")
'Retrieve the access token by using the authorization code:
RetVal = Client.ProcessUserAuthorization(authCode, state)
'store the refresh token
Call StoreRefreshToken(state.RefreshToken)
Return RetVal
End Function
Private Function LoadRefreshToken() As String
Return My.Settings.SavedAuth
End Function
Private Sub StoreRefreshToken(ByVal Token As String)
My.Settings("SavedAuth") = Token
My.Settings.Save()
End Sub
End Class

Upload and download to Google Drive using VB.NET Form [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
I am trying to figure out the codes for visual basic .net 2008 of a program (WinForms) that could upload and download some files to and from my google drive account.
Someone can help me?
It took a long time to find some code that worked and I never did find anything written in vb.net. Everything I found was written for C#. Well after doing a bunch of conversion I was able to get some things working. However it was very little and I had to figure out the rest. So to make other people's life so much easier here is working vb.net code for Drive v2 & OAuth 2.0:
Imports System.Threading
Imports System.Threading.Tasks
Imports Google
Imports Google.Apis.Auth.OAuth2
Imports Google.Apis.Drive.v2
Imports Google.Apis.Drive.v2.Data
Imports Google.Apis.Services
Imports Google.Apis.Auth
Imports Google.Apis.Download
'Dev Console:
'https://console.developers.google.com/
'Nuget command:
'Install-Package Google.Apis.Drive.v2
Private Service As DriveService = New DriveService
Private Sub CreateService()
If Not BeGreen Then
Dim ClientId = "your client ID"
Dim ClientSecret = "your client secret"
Dim MyUserCredential As UserCredential = GoogleWebAuthorizationBroker.AuthorizeAsync(New ClientSecrets() With {.ClientId = ClientId, .ClientSecret = ClientSecret}, {DriveService.Scope.Drive}, "user", CancellationToken.None).Result
Service = New DriveService(New BaseClientService.Initializer() With {.HttpClientInitializer = MyUserCredential, .ApplicationName = "Google Drive VB Dot Net"})
End If
End Sub
Private Sub UploadFile(FilePath As String)
Me.Cursor = Cursors.WaitCursor
If Service.ApplicationName <> "Google Drive VB Dot Net" Then CreateService()
Dim TheFile As New File()
TheFile.Title = "My document"
TheFile.Description = "A test document"
TheFile.MimeType = "text/plain"
Dim ByteArray As Byte() = System.IO.File.ReadAllBytes(FilePath)
Dim Stream As New System.IO.MemoryStream(ByteArray)
Dim UploadRequest As FilesResource.InsertMediaUpload = Service.Files.Insert(TheFile, Stream, TheFile.MimeType)
Me.Cursor = Cursors.Default
MsgBox("Upload Finished")
End Sub
Private Sub DownloadFile(url As String, DownloadDir As String)
Me.Cursor = Cursors.WaitCursor
If Service.ApplicationName <> "Google Drive VB Dot Net" Then CreateService()
Dim Downloader = New MediaDownloader(Service)
Downloader.ChunkSize = 256 * 1024 '256 KB
' figure out the right file type base on UploadFileName extension
Dim Filename = DownloadDir & "NewDoc.txt"
Using FileStream = New System.IO.FileStream(Filename, System.IO.FileMode.Create, System.IO.FileAccess.Write)
Dim Progress = Downloader.DownloadAsync(url, FileStream)
Threading.Thread.Sleep(1000)
Do While Progress.Status = TaskStatus.Running
Loop
If Progress.Status = TaskStatus.RanToCompletion Then
MsgBox("Downloaded!")
Else
MsgBox("Not Downloaded :(")
End If
End Using
Me.Cursor = Cursors.Default
End Sub
If you don't know the URL to download the file, then you can use this code to get one:
Dim Request = Service.Files.List()
Request.Q = "mimeType != 'application/vnd.google-apps.folder' and trashed = false"
Request.MaxResults = 2
Dim Results = Request.Execute
For Each Result In Results.Items
MsgBox(Result.DownloadUrl & vbCrLf & Result.Title & vbCrLf & Result.OriginalFilename)
Next
Please look at the .NET samples found on the Google Drive SDK website found below.
Google Drive SDK Documentation
using Google.Apis.Auth.OAuth2;
using Google.Apis.Drive.v3;
using Google.Apis.Drive.v3.Data;
using Google.Apis.Services;
using Google.Apis.Util.Store;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace DriveQuickstart
{
class Program
{
// If modifying these scopes, delete your previously saved credentials
// at ~/.credentials/drive-dotnet-quickstart.json
static string[] Scopes = { DriveService.Scope.DriveReadonly };
static string ApplicationName = "Drive API .NET Quickstart";
static void Main(string[] args)
{
UserCredential credential;
using (var stream =
new FileStream("credentials.json", FileMode.Open, FileAccess.Read))
{
// The file token.json stores the user's access and refresh tokens, and is created
// automatically when the authorization flow completes for the first time.
string credPath = "token.json";
credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
GoogleClientSecrets.Load(stream).Secrets,
Scopes,
"user",
CancellationToken.None,
new FileDataStore(credPath, true)).Result;
Console.WriteLine("Credential file saved to: " + credPath);
}
// Create Drive API service.
var service = new DriveService(new BaseClientService.Initializer()
{
HttpClientInitializer = credential,
ApplicationName = ApplicationName,
});
// Define parameters of request.
FilesResource.ListRequest listRequest = service.Files.List();
listRequest.PageSize = 10;
listRequest.Fields = "nextPageToken, files(id, name)";
// List files.
IList<Google.Apis.Drive.v3.Data.File> files = listRequest.Execute()
.Files;
Console.WriteLine("Files:");
if (files != null && files.Count > 0)
{
foreach (var file in files)
{
Console.WriteLine("{0} ({1})", file.Name, file.Id);
}
}
else
{
Console.WriteLine("No files found.");
}
Console.Read();
}
}
}
Hope this helps you.