Hangman System.IO.IOException' occurred in mscorlib.dll - vb.net

i am creating a hangman game that is to be used on a few computers, i have created the hangman game itself but i am using the "load form" function to create the list when the program first starts, but i am having this issue.
An unhandled exception of type 'System.IO.IOException' occurred in mscorlib.dll
Additional information: The process cannot access the file 'h:\Bryson\words.txt' because it is being used by another process.
Using sw As StreamWriter = File.CreateText("h:\Bryson\words.txt")
^^that line is where the error pops up^^
I have inserted some in code Comments to make life easier. If anyone can help thanks in advance :)
'USED TO CREATE HANGMAN FILE IF NOT FOUND
Private Sub main_Load(sender As Object, e As EventArgs) Handles MyBase.Load
fofound = False
fifound = False
MsgBox("remove this and change file path and fix qu2 quiz")
'DESIGNER USE
Dim path As String = "h:\Bryson\words.txt"
'CREATE VAR FOR PATH
If System.IO.Directory.Exists("h:\Bryson") Then
'CHECKS IF FOLDER EXISTS
fofound = True
Else
'IF IT DOES THEN IT MOVES ON
System.IO.Directory.CreateDirectory("h:\Bryson")
'IF NOT IT CREATES THE FOLDER
fofound = True
If File.Exists("h:\Bryson\test\words.txt") Then
'CHECKS IF FILE EXISTS
fifound = True
Else
'IF IT DOES IT MOVES ON
IO.File.Create("h:\Bryson\words.txt")
'IF NOT IT CREATES IT
FileClose()
End If
End If
If fofound And fifound = True Then
Else
Using sw As StreamWriter = File.CreateText("h:\Bryson\words.txt")
'CRASH POINT The process cannot access the file 'C:\Bryson\words.txt'
'because it Is being used by another process.
sw.WriteLine("Hangman")
sw.WriteLine("computer")
sw.WriteLine("electrode")
sw.WriteLine("independent")
sw.WriteLine("stream")
sw.WriteLine("enforcing")
End Using
'WRITES TO FILE
MsgBox("file created")
'DESIGNER USE
FileClose()
'CLOSES FILE
End If
End Sub

FileClose() is a legacy function from VB6 and will not affect anything in the System.IO namespace. To close a file you need to call .Close() or .Dispose() on the stream that has opened the file (wrapping the stream in a Using block does this automatically).
Your problem is this line:
IO.File.Create("h:\Bryson\words.txt")
The method creates a new file and opens a FileStream to it which locks the file. Since you never close the returned FileStream your file will remain locked until you close your application.
The File.Create() call is completely unnecessary though because File.CreateText() will create the file if it doesn't exist. So you should just remove the above line.

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.

How to Access a txt file in a Folder created inside a VB project

I'm creating a VB project for Quiz App (in VS 2013). So I have some preset questions which are inside the project (I have created a folder inside my project and added a text file).
My question is how can I read and write contents to that file? Or if not is there any way to copy that txt file to Documents/MyAppname when installing the app so that I can edit it from that location?
In the example below I am focusing on accessing files one folder under the executable folder, not in another folder else wheres. Files are read if they exists and then depending on the first character on each line upper or lower case the line then save data back to the same file. Of course there are many ways to work with files, this is but one.
The following, created in the project folder in Solution Explorer a folder named Files, add to text files, textfile1.txt and textfile2.txt. Place several non empty lines in each with each line starting with a character. Each textfile, set in properties under solution explorer Copy to Output Directory to "Copy if newer".
Hopefully this is in tune with what you want. It may or may not work as expected via ClickOnce as I don't use ClickOnce to validate this.
In a form, one button with the following code.
Public Class Form1
Private TextFilePath As String =
IO.Path.Combine(
AppDomain.CurrentDomain.BaseDirectory, "Files")
Private TextFiles As New List(Of String) From
{
"TextFile1.txt",
"TextFile2.txt",
"TextFile3.txt"
}
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim FileName As String = ""
' loop thru each file
For Each fileBaseName As String In TextFiles
FileName = IO.Path.Combine(TextFilePath, fileBaseName)
' only access file if it exist currently
If IO.File.Exists(FileName) Then
' read file into string array
Dim contents As String() = IO.File.ReadAllLines(FileName)
' upper or lower case line based on first char.
' this means you can flip flop on each click on the button
For x As Integer = 0 To contents.Count - 1
If Char.IsUpper(CChar(contents(x))) Then
contents(x) = contents(x).ToLower
Else
contents(x) = contents(x).ToUpper
End If
Next
' save changes, being pesstimistic so we use a try-catch
Try
IO.File.WriteAllLines(FileName, contents)
Catch ex As Exception
Console.WriteLine("Attempted to save {0} failed. Error: {1}",
FileName,
ex.Message)
End Try
Else
Console.WriteLine("Does not exists {0}", FileName)
End If
Next
End Sub
End Class
This may help you
Dim objStreamReader As StreamReader
Dim strLine As String
'Pass the file path and the file name to the StreamReader constructor.
objStreamReader = New StreamReader("C:\Boot.ini")
'Read the first line of text.
strLine = objStreamReader.ReadLine
'Continue to read until you reach the end of the file.
Do While Not strLine Is Nothing
'Write the line to the Console window.
Console.WriteLine(strLine)
'Read the next line.
strLine = objStreamReader.ReadLine
Loop
'Close the file.
objStreamReader.Close()
Console.ReadLine()
You can also check this link.

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

" A Sharing Violation occured" error when editing images in Paint using VB.NET

I have written a program in VB.NET to monitor file changes to recent saved screenshots taken from the tool.
I have a custom FileSystemWatcher class written (shared by someone on the internet,just customized) and have an instance invoked in my program.
The basic issue or objective is that when i capture a screen area using my program, I want it to immediately copy it over to clipboard. There are times when I would want to edit the captured image, in which case any editing made and saved, after saving the edited image must automatically be copied over to clipboard.
I use the below code to copy the image over to clipboard
'Subroutine to Copy the captured screenshot
'Added 15/09/2014
Sub CopyImageCapture(ByVal ImgPath)
Dim ThreadA As Thread
ThreadA = New Thread(AddressOf Me.MyAsyncTask)
'Setting ApartmentState.STA as this is needed for Clipboard related functionalities
ThreadA.SetApartmentState(ApartmentState.STA)
ThreadA.Start(ImgPath)
End Sub
'Threading to handle the Clipboard copy function
'Copy the screenshot to Clipboard
'Added 15/09/2014
Private Sub MyAsyncTask(ByVal ImgPath)
Clipboard.Clear()
Clipboard.SetImage(ImgPath)
End Sub
And when i choose to edit the image, the below code takes care to monitor the file changes
Sub MonitorFileChange(ByVal FolderPath, ByVal ItemName)
Try
Dim sFolder As String
Dim sFile As String
sFolder = FolderPath
sFile = ItemName
If IO.Directory.Exists(sFolder) Then
objWatcher.FolderToMonitor = sFolder
objWatcher.FileToMonitor = sFile
'objWatcher.NotifyFilter = (NotifyFilters.FileName Or NotifyFilters.Size)
objWatcher.StartWatch()
Else
MessageBox.Show("Folder does not exist!")
End If
Catch ex As Exception
MsgBox("Encountered an exception in MonitorFileChange subroutine. Details - " + ex.Message)
End Try
End Sub
'Subrountine to capture FileChanged events (esp. when captured image is edited in Paint and Saved)
'Works in sync with custom class 'clsFSW' for this purpose.
'ADDED: 15/09/2014
Private Sub objWatcher_FileChanged(ByVal FullPath As String) Handles objWatcher.FileChanged
'Try
Dim lastWriteTime As DateTime
lastWriteTime = File.GetLastWriteTime(FullPath)
Debug.Print(lastWriteTime)
If (lastWriteTime <> lastRead) Then
objWatcher.EnableRaisingEvents = False
'QuickCopy for changes files. BUG FIX
If (QuickSaveToolStripMenuItem.Checked) Then
Debug.Print("File Changed: " & FullPath & vbCrLf)
Dim tempI As System.Drawing.Bitmap = New System.Drawing.Bitmap(FullPath)
Dim tempI2 As System.Drawing.Bitmap = New System.Drawing.Bitmap(tempI, tempI.Width, tempI.Height)
CopyImageCapture(tempI2)
tempI.Dispose()
End If
lastRead = lastWriteTime
End If
'Catch ex As Exception
' MsgBox("Encountered an exception in objWatcher_FileChanged subrountine. Details - " + ex.Message)
' 'Finally
' 'objWatcher.EnableRaisingEvents = True
'End Try
End Sub
The problem is sometimes when I open the captured image and make quick saves or press save a couple of times real quick I get a "A Sharing violation occured" error
Can anyone help resolve the above issue? Which part of the code or logic is causing this to happen?
Also, if you check the above snippet, sometimes (havent seen any particular pattern) but the catch block in objWatcher_FileChanged is triggered and the error is "Parameter not found"
Can someone please help into this too?
Thanks in advance! Please let me know if any info more is required.
EDIT: Please note, the sharing violation error seems invoked from the Paint application itself and not my program, but why does it happen randomly, is a mystery to me. Is there nay loophole in the logic? Any alternative logic to what I want to achieve?
Try disposing tempI2. Windows may be locking the file used with tempI, and keeping it locked since it is assigned to tempI2. If so, it may remain locked until tempI2 is disposed.

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.