VB.net UploadFile - vb.net

I am trying to send a file up to a server using VB.net. I have found many examples exclaiming it to be simple to do but none of the examples I have found have worked.
The current one I am trying is in the following code:
Dim WithEvents wc As New System.Net.WebClient()
Private Sub oWord_DocumentBeforeClose(ByVal Doc As Microsoft.Office.Interop.Word.Document, ByRef Cancel As Boolean) Handles oWord.DocumentBeforeClose
Try
Using wc As New System.Net.WebClient()
wc.Credentials = New NetworkCredential("ehavermale", "ernie1")
wc.UploadFile("http://192.168.95.1:83/GraphTest.txt", "C:\Users\EHovermale\Desktop\GraphTest.txt")
End Using
Catch ex As Exception
MsgBox("Error:" + ex.Message)
End Try
'System.IO.File.Delete("C:\Users\EHovermale\Desktop\GraphTest.txt")
MsgBox("See Ya")
End Sub
When I run this program I get the Error: An Exception has occurred during a WebClient Request.
I have access to read/write files to the server I am trying to hit.
Is there another way to upload files or is something wrong with my code for this way?
Thank you!

Since there is no HTTP service to handle the file upload, you could save the file directly using VBA's Scripting.FileSystemObject. This will work if you can access the network share from wherever your document is located. Remember that if the document is moved to another computer then this may not work.
Public Sub MoveFile()
Dim fso As Object
Dim sourceFile As String
Dim targetFile As String
' You must add reference to "Microsoft Scripting Runtime" to your document
' Tools > References... > scroll down the item.
Set fso = CreateObject("Scripting.FileSystemObject")
sourceFile = "C:\Users\davidr\Desktop\foo.txt"
targetFile = "\\192.168.95.1:83\foo.txt"
' Test if destination file already exists
If fso.FileExists(targetFile) Then
MsgBox ("This file exists!")
Exit Sub
End If
' Move the file
fso.CopyFile sourceFile, targetFile
Set fso = Nothing
End Sub

Related

Close Excel Workbook If Test for Open Returns False

I've constructed a VB.Net application which loads data into an Excel spreadsheet. The application works fine, but I've added a functionality to test whether the workbook is Open, and if so, the application terminates. Otherwise, if the workbook Is Not Open, then the user can proceed to fill information in the application. My issue is that when is when the worksheet is not open, my code blows up due to the workbook being "somehow opened." I need to close any processes, then proceed. Here's my code for checking if the workbook is open or not:
1st, my module, which sets up the a Boolean check:
Public Module ExcelCheck
Public Function Test(ByRef sName As String) As Boolean
Dim fs As FileStream
Try
fs = File.Open(sName, FileMode.Open, FileAccess.Read, FileShare.None)
Test = False
Catch ex As Exception
Test = True
End Try
End Function
End Module
Then my handler for a button on the form that does the check:
Private Sub btnOpenFileCheck_Click(sender As Object, e As EventArgs) Handles btnOpenFileCheck.Click
'Evaluate if the workbook is being used:
Dim bExist As Boolean
bExist = Test("\\netshareA\c$\Users\Pete\Desktop\TestUnits\Machines.xls")
If bExist = True Then
MessageBox.Show("The file is open... Please try again later.", "EXCEL FILE IN USE: Abort", MessageBoxButtons.OK)
Me.Close()
Else bExist = False
MessageBox.Show("The file is NOT open... You may proceed...", "EXCEL FILE NOT OPEN", MessageBoxButtons.OK)
Dim xlOpenItem As New Excel.Application
Dim xlOpenWB As Excel.Workbook = xlOpenItem.Workbooks.Open("\\netshareA\c$\Users\Pete\Desktop\TestUnits\Machines")
xlOpenWB.Close(SaveChanges:=False, Filename:="\\netshareA\c$\Users\Pete\Desktop\TestUnits\Machines.xls", RouteWorkbook:=False)
txtCPUSerial.Focus()
End If
End Sub
What happens when the book isn't open is the proper dialog to continue runs via the illustration:
But then an Excel dialog appears saying the following:
'\\netshareA\c$\Users\Pete\Desktop\TestUnits\Machines.xls'
is currently in use. Try again later.
Then, it finally blows up and I have the line of referenced:
Dim xlOpenWB As Excel.Workbook = xlOpenItem.Workbooks.Open("\\netshareA\c$\Users\Pete\Desktop\TestUnits\Machines")
My logic is that I need to have an open instance of an Excel object, then close that instance in order to terminate any inadvertent running process. I actually open the workbook in another submit handler, with the Excel objects and variables set well, but that's not my issue. How can I smoothly make sure the workbook object is closed here as as to not throw an exception that it isn't?
After much tinkering around, I've found out exactly what my problem was - I didn't close out the opened file stream:
Public Module ExcelCheck
Public Function Test(ByRef sName As String) As Boolean
Dim fs As FileStream
Try
fs = File.Open(sName, FileMode.Open, FileAccess.Read, FileShare.None)
Test = False
fs.Close() 'This closes out the initially opened file stream for checking.
Catch ex As Exception
Test = True
End Try
End Function
End Module
I eventually came back to the module and wondered what happens if I just close out and use fs.Close() and it did the trick. No more blow ups! Hope this helps someone else whom might struggle with a similar file stream issue.

Detect if any file in use by other process of a directory in VB

I am trying to get my vb.net application to look inside a folder and then let me know whether any file older is in use by any application. If in use it will show a message box. I am coding in VB.NET 2008, Express Edition. ...Would anybody know how I do that? Thanks
You can extend the suggested solution with enumerating files in a directory.
Imports System.IO
Imports System.Runtime.InteropServices
Module Module1
Sub Main()
' Here you specify the given directory
Dim rootFolder As DirectoryInfo = New DirectoryInfo("C:\SomeDir")
' Then you enumerate all the files within this directory and its subdirectory
' See System.IO.SearchOption enum for more info
For Each file As FileInfo In rootFolder.EnumerateFiles("*.*", SearchOption.AllDirectories)
' Here you can call the method from the solution linked in Sachin's comment
IsFileOpen(file)
Next
End Sub
' Jeremy Thompson's code from here
Private Sub IsFileOpen(ByVal file As FileInfo)
Dim stream As FileStream = Nothing
Try
stream = file.Open(FileMode.Open, FileAccess.ReadWrite, FileShare.None)
stream.Close()
Catch ex As Exception
If TypeOf ex Is IOException AndAlso IsFileLocked(ex) Then
' do something here, either close the file if you have a handle, show a msgbox, retry or as a last resort terminate the process - which could cause corruption and lose data
End If
End Try
End Sub
Private Function IsFileLocked(exception As Exception) As Boolean
Dim errorCode As Integer = Marshal.GetHRForException(exception) And ((1 << 16) - 1)
Return errorCode = 32 OrElse errorCode = 33
End Function
End Module

Renaming File Error: The process cannot access the file because it is being used by another process

I am creating an application that allows the user to preview files using Web Browser Control in vb.net and also allow to input some other details using textbox. After the details was saved, the file will be removed from the list and will be added to the list of finished files and will be automatically renamed. The problem is, when I am trying to rename the file, an exception occur stating "The process cannot access the file because it is being used by another process." How can I terminate the process for me to able to rename the file?
Original_File: it is the complete destination and filename.
SelectedFile: it is the filename.
ClearEmpData: clear the fields.
Private Sub btnSave_Emp_Click(sender As Object, e As EventArgs) Handles btnSave_Emp.Click
Dim SP_Name As String = "SP_EmpData"
Dim SP_Param As String() = {"#DType", "#Equip", "#EmpNo", "#LN", "#FN", "#Path"}
Dim SP_Val As String() = {cbDataType_emp.Text, Equipment_Type, Emp_No, LastName, FirstName, New_Path}
If cbDataType_emp.SelectedIndex <= 0 Then
MyFile.Message.ShowEntryError("Please select data type.", cbDataType_emp)
Exit Sub
Else
If Not MyFile.Process.MoveFiles(Root_Dir, dgvEncode.SelectedCells.Item(1).Value, cbDocType.Text) Then Exit Sub
If Not ExecuteSaveProcedure(SP_Name, SP_Param, SP_Val) Then Exit Sub
Original_File = dgvEncode.SelectedCells.Item(2).Value
Dim dr As DataGridViewRow
For Each dr In dgvEncode.SelectedRows
dgvEncode.Rows.Remove(dr)
dgvDone.Rows.Add(dr)
Next
dgvEncode.CurrentCell.Selected = dgvEncode.Rows.Count
ClearEmpData()
dgvDone.ClearSelection()
Try
My.Computer.FileSystem.RenameFile(Original_File, "xDone_" & SelectedFile)
Catch ex As Exception
MyFile.Message.ShowWarnning(ex.Message)
Exit Sub
End Try
End If
End Sub
I already solved this problem. I created a temporary file to be preview then rename the original file and then delete the temporary file.

Use Shell32.dll on mix of XP, Vista, Win7 via XCOPY deploy

I'm trying to use Shell32.dll to unzip a simple compressed file. I have a reference to Shell32.dll which shows up as Interop.Shell.dll on my development PC (Win7 64.) I push exe updates out via file copy from a central location and I would like to do this for the .dll as well.
The program fails on XP using the same file as it installed on my PC. I tried using a Shell.dll from the XP \Windows\System renamed to Interop.Shell.dll but I guess that would be to simple - it gets an error that it cannot load when I try to invoke the dll.
I'm open too another way of doing unzip that uses a dll that is agnostic as to platform. I've used 7Zip via Process.Start() but I'd like to avoid having to install/update a program on the clients.
Is there a common denominator Shell32.dll I could use the would run on any Win OS on/after XP?
Or do I have to create a separate build for each OS if I use Shell32.dll?
Thanks!
Function Unzip(FilePathofZip As String, DestinationFolder As String) As Boolean
Try
Dim sFile As String = FilePathofZip
' requires referenc to windows.system.shell32.dll
Dim sc As New Shell32.Shell()
If IO.Directory.Exists(DestinationFolder) Then IO.Directory.Delete(DestinationFolder, True)
Application.DoEvents()
IO.Directory.CreateDirectory(DestinationFolder)
'Declare the folder where the files will be extracted
Dim output As Shell32.Folder = sc.NameSpace(DestinationFolder)
If FilePathofZip.EndsWith(".kmz") Then
sFile = FilePathofZip & ".zip"
IO.File.Move(FilePathofZip, sFile)
Application.DoEvents()
End If
'Declare your input zip file as folder
Dim input As Shell32.Folder = sc.NameSpace(sFile)
'Extract the files from the zip file using the CopyHere command .
output.CopyHere(input.Items, 4)
Return True
Catch ex As Exception
MsgBox(ex.Message)
Return False
End Try
End Function
I switched to DotNetZip. Add Project Reference to the Ionic.Zip.Reduced.dll. Imports Ionic.Zip
This code is expecting .kmz files downloaded from ESRI REST services but should work with .zip files as well.
Function Unzip(FilePathofZip As String, DestinationFolder As String) As Boolean
' extract .kmz files downloaded from ESRI REST services
Try
Dim sFile As String = FilePathofZip
If IO.Directory.Exists(DestinationFolder) Then IO.Directory.Delete(DestinationFolder, True)
Application.DoEvents()
IO.Directory.CreateDirectory(DestinationFolder)
If FilePathofZip.EndsWith(".kmz") Then
sFile = FilePathofZip & ".zip"
IO.File.Move(FilePathofZip, sFile)
Application.DoEvents()
End If
Try
' Using... required
Using zip As ZipFile = ZipFile.Read(sFile)
Dim e As ZipEntry
For Each e In zip
e.Extract(DestinationFolder)
Next
End Using
Catch ex1 As Exception
MsgBox("Problem with compressed file - notify programmers" & vbCrLf & ex1.Message)
Return False
End Try
Return True
Catch ex As Exception
MsgBox(ex.Message)
Return False
End Try
End Function

ASP.NET How do I wait for file upload/release?

I've got ASP.NET intranet application written in VB. It gets a file from the user, and then depending on a few different cases it may create a few copies of the file as well as move the original.
Unfortunately I've come across a case where I get this error:
Exception Details: System.IO.IOException: The process cannot access the file
'\\some\dir\D09_03_5_180_0.000-6.788.png' because it is being used by
another process.
Which is thrown by My.Computer.FileSystem.CopyFile. And that's fine that it's being used by another process - it may still be saving/downloading from the user or trying to copy while another thread(?) is copying, I don't really care about that, what I want to know:
Is there any way that I can tell VB to wait to copy (also move) the file until the file is no longer in use?
Thanks
Test if the file is in use and the do what you need to do.
Public Sub WriteLogFile(ByVal pText As String, ByVal psPath As String, ByVal psName As String)
Dim strFullFileName As String
Dim Writer As System.IO.StreamWriter
Dim Fs As System.IO.FileStream
Try
Dim DirectoryHandler As New System.IO.DirectoryInfo(psPath)
strFullFileName = psPath & "\" & psName & Date.Today.Month.ToString & "-" & Date.Today.Day.ToString & "-" & Date.Today.Year.ToString & ".txt"
If Not DirectoryHandler.Exists() Then
Try
Monitor.Enter(fsLocker)
DirectoryHandler.Create()
Finally
Monitor.Exit(fsLocker)
End Try
End If
Try
If CheckIfFileIsInUse(strFullFileName) = True Then
Thread.Sleep(500) ' wait for .5 second
WriteLogFile(pText, psPath, psName)
If Not Fs Is Nothing Then Fs.Close()
If Not Writer Is Nothing Then Writer.Close()
Exit Sub
End If
Monitor.Enter(fsLocker)
Fs = New System.IO.FileStream(strFullFileName, IO.FileMode.Append, IO.FileAccess.Write, IO.FileShare.Write)
Writer = New System.IO.StreamWriter(Fs)
Writer.WriteLine(Date.Now.ToString & vbTab & "ProcessID: " & Process.GetCurrentProcess.Id.ToString() & vbTab & pText)
Writer.Close()
Fs.Close()
Finally
Monitor.Exit(fsLocker)
End Try
Catch ex As Exception
Dim evtEMailLog As System.Diagnostics.EventLog = New System.Diagnostics.EventLog()
evtEMailLog.Source = Process.GetCurrentProcess.ProcessName.ToString()
evtEMailLog.WriteEntry(ex.Message, System.Diagnostics.EventLogEntryType.Error)
Finally
If Not Fs Is Nothing Then Fs.Close()
If Not Writer Is Nothing Then Writer.Close()
End Try
End Sub
Public Function CheckIfFileIsInUse(ByVal sFile As String) As Boolean
If System.IO.File.Exists(sFile) Then
Try
Dim F As Short = FreeFile()
FileOpen(F, sFile, OpenMode.Append, OpenAccess.Write, OpenShare.Shared)
FileClose(F)
Catch
Return True
End Try
End If
End Function
Hmm... not directly.
What most implementations are doing, is making a retry of copying the file, with a small timeframe (some seconds)
if you want to make a nice UI, you check via Ajax, if the copying process went well.
Well, it turns out that waiting would not work in this case:
When trying to copy a file you cannot copy a file from one location to the same location or it will throw an error (apparently). Rather than just pretending to copy the file, VB actually tries to copy the file and fails because the copy operation is trying to copy to the file it's copying from (with overwrite:=True at least).
Whoops!