Identifying if a JPG file is open - vb.net

I've been trying to set an error trap that will detect if a file is already open. This is no problem when the file is a text file using the following code:
Private Function FILEOPEN(ByVal sFile As String) As Boolean
Dim THISFILEOPEN As Boolean = False
Try
Using f As New IO.FileStream(sFile, IO.FileMode.Open)
THISFILEOPEN = False
End Using
Catch
THISFILEOPEN = True
End Try
Return THISFILEOPEN
End Function
My problem is that when the file is an open JPG file, not a text file, the above function returns False indicating that it is not open? I have tried different variations of the function but still cannot find a function that can tell if a JPG file is open.

You should NOT do this kind of behavior. Simple answer is because after you check, but before you do anything with it, the file may become unavailable. A proper way is to handle an exception as you access the file. You may find this answer helpful:
https://stackoverflow.com/a/11288781/897326

Related

VB 2012 - StreamReader not closing

This is a real head scratcher. According to all documentation, file.readAllLines should close the file it's reading from after it completes. But in my app, when I try to write to the file, it throws an IO exception saying "process cannot access the file because it is being used by another process". And this should be really simple - the file in question is only referenced twice - once when it's read into the app on first start, and then when you overwrite it. Here's the code:
Firstly, the code that opens the file (filepath used is c:\Test\cfg.fcs):
Public Function ReadALine(ByVal File_Path As String, ByVal TotalLine As Integer, ByVal Line2Read As Integer) As String
Dim Buffer As Array
Dim Line As String
If TotalLine <= Line2Read Then
Return "No Such Line"
End If
Buffer = File.ReadAllLines(File_Path)
Line = Buffer(Line2Read)
Return Line
End Function
It works perfectly, and should leave the file properly closed, right? but when I run the following a bit later in another module:
file = My.Computer.FileSystem.OpenTextFileWriter("c:\Test\cfg.fcs", False)
file.WriteLine(Form1.GlobalVariables.serialNumber)
it throws an exception saying the file's still in use. Those are the only two times in the whole app that file is even mentioned.
for anyone else running into this problem the solution was simple but still counterintuitive... the problem was only the sequence of the commands. I moved the file.writeline down to the bottom of the suband for some reason that fixed it. strange

WebClient.DownloadFile convert to File VB.NET

Does anyone know how to parse a Webclient.DowloadFile to File in VB.Net?
I'm currently using the following Code but I keep getting the errors:
(BC30491) Expression does not produce a value.
(BC30311) Value of Type can not be converted to File
Private Function DepartmentDataDownloader() As String
Dim webClient As New System.Net.WebClient
'I get here the error BC30491
Dim result As File = webClient.DownloadFile("https://intern.hethoutsemeer.nl/index2.php?option=com_webservices&controller=csv&method=hours.board.fetch&key=F2mKaXYGzbjMA4V&element=departments", "intern.hethoutsemeer.nl.1505213278-Departments.csv")
If webClient IsNot Nothing Then
'and here BC30311
Dim result As File = webClient
UploaderFromDownload(webClient)
End If
Return ""
End Function
The DownloadFile method doesn't return a value, because DownloadFile is a Sub. This is the reason why you get the BC30491 error. The second parameter specifies the path of the local file (and the result of the download).
So you can try something like the following:
Dim webClient As New System.Net.WebClient
'after this the file specified on second parameter should exists.
webClient.DownloadFile("https://intern.hethoutsemeer.nl/index2.php?option=com_webservices&controller=csv&method=hours.board.fetch&key=F2mKaXYGzbjMA4V&element=departments", "intern.hethoutsemeer.nl.1505213278-Departments.csv")
If webClient IsNot Nothing Then
'do something with the downloaded file (File.OpenRead(), File.*).
'Dim result As File
UploaderFromDownload(webClient)
End If
You also try to assign the WebClient value to a File variable. This is not possible so you get the BC30311 error.
Hint: You can't create an instance of the File class. The File class provides static methods for the creation, copying, deletion, moving, and opening of a single file, and aids in the creation of FileStream objects.
source: https://learn.microsoft.com/en-us/dotnet/api/system.io.file

How to check if file (.wav) is opened and then play file

I am currently working on a console application to play a freshly created WAV RIFF file, and then delete it. Like I said, it is freshly created, so I need to make sure the file isn't being edited before I start playing it or it will be corrupted. After it plays, I delete it.
Currently, my code looks like this (using System.IO):
Sub Main()
Dim fileName As String
fileName = "C:\temp\Burst\Burst.wav"
While CheckFile(fileName)
End While
Try
My.Computer.Audio.Play(fileName, AudioPlayMode.WaitToComplete)
Catch ex As Exception
Console.WriteLine(ex.Message)
End Try
My.Computer.FileSystem.DeleteFile(fileName)
End Sub
Private Function CheckFile(ByVal filename As String) As Boolean
Try
System.IO.File.Open(filename, IO.FileMode.Open, IO.FileAccess.Read, IO.FileShare.None)
FileClose(1)
Return False
Catch ex As Exception
Return True
End Try
End Function
The function I am using to check if the file is opened was created by sealz. I found it here. Unfortunately, however, this function is causing an exception in that after it runs, the program cannot access the file because it is being used by another process. If I remove this function, the file can be opened, played and deleted.
The exception reads as follows:
An unhandled exception of type'System.IO.IOException' occurred in mscorlib.dll Additionalinformation: The process cannot access the file 'C:\temp\Burst\burst.wav' because it is being used by another process.
So the function that is supposed to help determine if the file is being used, is actually causing the file to be opened. It seems like it isn't closing. Is there anyway I can modify this current function to work properly for my application or are there any other ideas on how to tackle this. Thanks for your time.
-Josh
Here is your problem:
System.IO.File.Open(filename, IO.FileMode.Open, IO.FileAccess.Read, IO.FileShare.None)
FileClose(1)
Return False
A Using will help:
Using _fs as System.Io.FileStream = System.IO.File.Open(filename, IO.FileMode.Open, IO.FileAccess.Read, IO.FileShare.None)
End Using
Return False
File.Open Returns a Filestream, not an Integer needed for FileClose
As far as I get you are trying to check if file exists before playback using System.IO.File.Open however you may do it with File.Exists.
Method File.Exists from System.IO returns true if file exists on path and returns false the otherwise.
Also you are doing it wrong here,
While CheckFile(fileName)
End While
If file is found it will enter into an infinite loop without doing anything other than calling CheckFile repeatedly. If file is not found, it will get out of loop and attempt Audio.Play and FileSystem.DeleteFile and you end up getting a file not found exception.
Here is your code modified and working.
Imports System.IO
Module Module1
Sub Main()
Dim fileName As String
fileName = "C:\temp\Burst\Burst.wav"
While CheckFile(fileName)
Try
My.Computer.Audio.Play(fileName, AudioPlayMode.WaitToComplete)
'Delete statement here if you want file to be deleted after playback
Catch ex As Exception
Console.WriteLine(ex.Message)
End Try
End While
My.Computer.FileSystem.DeleteFile(fileName)
Console.ReadLine()
End Sub
Private Function CheckFile(ByVal filename As String) As Boolean
If (File.Exists(filename)) Then
Return True
Else
Return False
End If
End Function
End Module

VB.NET - Check if URL is a directory or file

Is there a way, in VB.NET, to check if a URL is a directory? I've seen a lot of methods of checking if a local path is a directory but what about a remote url (i.e. http://website.com/foo) I read that some plain text files have no extension so I need a solution other than checking what if the file name contains a space or something.
You can use FileAttributes class:
'get the file attributes for file or directory
FileAttributes attr = File.GetAttributes("c:\\Temp")
'detect whether its a directory or file
If ((attr & FileAttributes.Directory) = FileAttributes.Directory) Then
MessageBox.Show("Its a directory")
Else
MessageBox.Show("Its a file")
End IF
Or you can use the Uri class:
Private IsLocalPath(Byval p As String) As Boolean
Return New Uri(p).IsFile
End Function
You can enhance this method to include support for certain invalid URIs:
Private IsLocalPath(Byval p As String) As Boolean
If (p.StartsWith("http:\\")) Then
Return False
End IF
Return New Uri(p).IsFile
End Function
The only solution I can think of is to try to download the file from the Internet, if the download succeeded So it is a file, otherwise it is not a file (but you don't know for sure that this is a directory).
This worked for me...
If System.IO.Path.HasExtension(FileAddress.Text) Then
MessageBox.Show("Its a file")
Else
MessageBox.Show("Its a directory")
End IF

VB.NET Checking if a File is Open before proceeding with a Read/Write?

Is there a method to verify that a file is open? The only thing I can think of is the Try/Catch to see if i can catch the file-open exception but I figured that a method be available to return true/false if file is open.
Currently using System.IO and the following code under class named Wallet.
Private holdPath As String = "defaultLog.txt"
Private _file As New FileStream(holdPath, FileMode.OpenOrCreate, FileAccess.ReadWrite)
Private file As New StreamWriter(_file)
Public Function Check(ByVal CheckNumber As Integer, ByVal CheckAmount As Decimal) As Decimal
Try
file.WriteLine("testing")
file.Close()
Catch e As IOException
'Note sure if this is the proper way.
End Try
Return 0D
End Function
Any pointers will be appreciated! Thank you!!
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 Shared 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
Call it like this:
Call IsFileOpen(new FileInfo(filePath))
There is really no point using a 'is file in use check' function since you will still need to have try catch to handle the case that the file fails to open. The file open can fail for many more reasons than it just being already open.
Also using a function to do a check is no guarantee of success. The 'is file in use check' might return false only for the file open to fail with a file already open error, because in time between the check and trying to open the file it was opened by someone else.
It looks like the two suggestions from this MSDN forum posting both involve trying to open the file.
The first one is similar to what you are doing now, and the second involves using a Windows API function (CreateFile) and checking for a invalid handle signifying the file is in use. In both cases they are relying on an error condition to determine if the file is open or not. In short, in my opinion the method you are using is correct since there is not a System.IO.File.IsOpen property.