upload files to dropbox using dropbox api - vb.net

i'm working in a console app that is going to be executed in a server every week, basically it generates a report in excel and then it has to upload it to a folder in dropbox, i've trying a lot of stuff for that last part i finally got this code that does not work but doesn't throw any exception (before i had one that throw and invalid folder format)
Dim _path As String
_path = "/Pruebas/" & Path.GetFileName(FilePath)
Try
Dim rawData = File.ReadAllBytes(FilePath)
Dim str = System.Text.Encoding.Default.GetString(rawData)
Using mem = New MemoryStream(Encoding.UTF8.GetBytes(str))
Dim Up = I.Files.UploadAsync(_path, body:=mem)
MsgBox("Successfully Uploaded")
End Using
Catch ex As Exception
MsgBox(ex.Message)
End Try
it doesn't throw exception but also doens't work, any help i'll be thankfull.

try this.
Dim Up = I.Files.UploadAsync(_path, WriteMode.Overwrite.Instance, body:=mem)
Link to documentation: http://dropbox.github.io/dropbox-sdk-dotnet/html/M_Dropbox_Api_Files_Routes_FilesUserRoutes_UploadAsync_1.htm

Related

How to upload file on Google Drive using vb.net?

I need help uploading the file to Google Drive.
Everything works fine but with an error during first trial.
During the debug at request.upload the cursor don't wait (wait for the file to upload) and skips to the next line Dim responsefile As New Data.File and I get nothing in request.ResponseBody.
After that I run the function cursor actually waits on request.upload and it uploads file successfully.
I don't know what is actually happening. I checked the data every time and it is the same.
Public Async Function UploadFile3(service As DriveService, FilePath As String) As Tasks.Task(Of Data.File)
If service3.ApplicationName <> "netGDriveApi" Then CreateService()
If IO.File.Exists(FilePath) Then
Dim body As New Data.File()
body.Name = IO.Path.GetFileName(FilePath)
body.Description = "BackUP file"
body.MimeType = "application/octet-stream"
'body.FileExtension = ".bak"
'-------------------------------------------------UPLOAD FILE PROCESS-------------------------------------------------------------
Dim byteArray As Byte() = IO.File.ReadAllBytes(FilePath)
Dim stream As New IO.MemoryStream(byteArray)
Try
Dim request As FilesResource.CreateMediaUpload = service.Files.Create(body, stream, body.MimeType)
Await request.UploadAsync() 'Cursor skips first time here and dont wait for response.
Dim responsefile As New Data.File 'Cursor waits from the above step to here till the file uploaded.
responsefile = request.ResponseBody
If IsNothing(responsefile) Then
MessageBox.Show("Try Again")
Else
MessageBox.Show(responsefile.Id.ToString)
End If
Catch e As Exception
MessageBox.Show("An error occurred: " + e.Message)
Return Nothing
End Try
Else
MessageBox.Show("FILE DOES NOT EXISTS." + FilePath)
Return Nothing
End If
End Function
request.UploadAsync() returns a Task(Of IUploadProgress). At the very least, you should be examining the result of this task. It might give you clues as to the cause of your problems.
For example, while debugging you could do something like the following:
Try
Dim request As FilesResource.CreateMediaUpload = service.Files.Create(body, stream, body.MimeType)
Dim Upload As IUploadProgress = Await request.UploadAsync() 'Cursor skips first time here and dont wait for response.
If Upload.Status <> UploadStatus.Completed Then
Dim ex As Exception = Upload.Exception
MessageBox.Show(ex.Message, "UploadAsync Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
Return Nothing
Else
MessageBox.Show(Upload.Status.ToString, "Upload Status:")
End If
Dim responsefile As New Data.File 'Cursor waits from the above step to here till the file uploaded.
responsefile = request.ResponseBody
Always check what information methods return, and use that information as necessary in your production code.
The line Dim request As FilesResource.CreateMediaUpload = service.Files.Create(body, stream, body.MimeType). Problem is here.
Thanks to #stevec to guide me the error.
The drive service is service3 and in the above line its just written service.Files.Create.
So the actual rectified answer is
Dim request As FilesResource.CreateMediaUpload = service3.Files.Create(body, stream, body.MimeType)

When writing to a file, how do I correctly resolve access to path is denied?

Here is my code:
Dim htmlFile = "\\folder\test.htm"
If File.Exists(htmlFile) Then
File.Delete(htmlFile)
End If
Using strWriter As StreamWriter = New StreamWriter(htmlFile, False)
strWriter.Write("content")
End Using
It works most of the time but occasionally I'll get an exception of "Access to the path '\folder\test.htm' is denied." The exception occurs on this line:
Using strWriter As StreamWriter = New StreamWriter(fileName, False)
How can I ensure that it always creates a new file and never causes an exception?
This routine waits some time in case of error betweens 2 servers writing the same file:
Retry_IT:
try
Dim htmlFile = "\\folder\test.htm"
If File.Exists(htmlFile) Then
File.Delete(htmlFile)
End If
Using strWriter As StreamWriter = New StreamWriter(htmlFile, False)
strWriter.Write("content")
End Using
Catch Exception
Thread.sleep(2000) '2 seconds
Goto Retry_It
End Try

File.Copy not working - no error

Please take a look at this code. For some reason that I can't figure out, the File.Delete() line isn't getting fired and I'm not getting an error.
' hard-coded for testing
Dim path As String = "C:\Program Files (x86)\Test\Program\Program.exe"
Dim appDir As String = My.Application.Info.DirectoryPath
Dim iniPath As String = appDir & "\config.ini"
Dim outputPath As String = appDir & "\output.ini"
Dim textLine As String = ""
Dim reader = File.OpenText(iniPath)
Dim writer = New StreamWriter(outputPath)
' Read the lines in the ini file until the pathToExecutable line is found and write the path to that line
While (InlineAssignHelper(textLine, reader.ReadLine())) IsNot Nothing
If textLine.StartsWith("pathToExecutable=") Then
writer.WriteLine("pathToExecutable=" & path)
Else
writer.WriteLine(textLine)
End If
End While
reader.Dispose()
reader.Close()
writer.Dispose()
writer.Close()
File.Copy(outputPath, iniPath, True)
File.Delete(outputPath) ' THIS ISN'T GETTING FIRED
Return path
You stated that you are not getting an error, but if you don't implement exception handling, you're most probably getting errors and throwing them away (pun intended).
Use a try/catch around any of your System.IO.File operations, and even more, you can implement specific handles and catch specific exceptions.
Try
File.Copy(outputPath, iniPath, True)
File.Delete(outputPath) ' THIS ISN'T GETTING FIRED
Catch ioException As IOException
'The specified file is in use.
MessageBox.Show(ioException.Message)
Catch ex As Exception
'Some other error apart for file in use.
MessageBox.Show(ex.Message)
End Try
Ericosg's suggestion about using a try/catch lead me to the issue: I had the file open in a streamreader earlier in my code, but never closed it there.

FileExist not working vb.net

I really can not understand why the exception is triggered.
I created this code that performs some checks for the correctness of the license.
The function isittrial occurs if the trial software is creating a hidden file, this file is then checked with File.exist.
The problem is the following:
the file is created by isittrial but for some strange reason you enable the exception of file.exist, what can I do to fix it?
I really can not understand why it does not work.
isittrial() 'this function make the file to check
Dim percorsoCompleto As String = System.Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData) + "\Software\cc.txt"
Try
If My.Computer.FileSystem.FileExists(directory) Then
Dim fileReader As String
Dim dire As String = System.Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData) + "\Software\cc.txt"
fileReader = My.Computer.FileSystem.ReadAllText(directory,
System.Text.Encoding.UTF32)
Dim check = DeCryptIt(fileReader, "aspanet")
Dim datadecripted As String = DeCryptIt(Registry.GetValue("HKEY_CURRENT_USER\Software\cc", "end", ""), "aspanet")
If Date.Now < check And check <> datadecripted Then
MsgBox("License not valid", MsgBoxStyle.Critical, "Attention!")
DeActivate()
ForceActivation()
Else
End If
Else
MsgBox("License not valid", MsgBoxStyle.Critical, "Attention!")
DeActivate()
ForceActivation()
End If
Catch ex As Exception
MsgBox("License not valid", MsgBoxStyle.Critical, "Attention!")
'DeActivate()
'ForceActivation()
End Try
This line
If My.Computer.FileSystem.FileExists(directory) Then
seems to test for the existence of a file passing the name of a directory (or an empty string or whatever, we can see how this variable is initialized). In every case the result will be false.
Then your code jumps to an else block with the same error message of the exception fooling your perception of the error.
Try instead
Dim percorsoCompleto As String = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData)
percorsoCompleto = Path.Combine(percorsoCompleto, "Software", "cc.txt")
Try
If My.Computer.FileSystem.FileExists(percorsoCompleto) Then
Dim fileReader As String
fileReader = My.Computer.FileSystem.ReadAllText(percorsoCompleto,
System.Text.Encoding.UTF32)
.....
Notice that I have removed the path concatenation with a more fail safe call to Path.Combine

vb.net Aspose.OCR - Extract text from Image

i tried to extract text from image by Aspose.OCR,
my code:
Const resourceFileName As String = "c:\2011.08.05 v1.1 Aspose.OCR.Resouces.zip"
Dim uploadedImage As String = "c:\ConvertMeToText.bmp"
Try
'Create OcrEngine instance and assign
'image, language and image configuration
Dim ocr As New OcrEngine()
ocr.Image = ImageStream.FromFile(uploadedImage)
ocr.Languages.AddLanguage(Language.Load("english"))
ocr.Config.NeedRotationCorrection = True
ocr.Config.UseDefaultDictionaries = True
Dim fileStream As New FileStream(resourceFileName, FileMode.Open)
ocr.Resource = fileStream
Try
If ocr.Process() Then
TextBox1.Text = ocr.Text.ToString()
End If
Catch ex As Exception
MsgBox("Exception: " & ex.Message)
End Try
fileStream.Close()
ocr = Nothing
Catch ex As Exception
MsgBox("Exception: " & ex.Message)
End Try
Exception:
ZipEntry::ReadHeader(): Bad signature (0x00000100) at position 0x00000000
my name is Nayyer and I work as a support developer / Technical Evangelist at Aspose.
From exception, it looks like there is some difference in Aspose.OCR version and resource file version. Every Aspose.OCR release uses a separate resources.zip file and if you try to use Aspose.OCR v1.0.0 with 2011.08.05 v1.1 Aspose.OCR.Resouces.zip then you might get similar exception. May be you can try the latest version of Aspose.OCR v.1.1.0 and its compatible resource file is available over this link.