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

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.

Related

Hangman System.IO.IOException' occurred in mscorlib.dll

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.

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.

Uploadfile method to overwrite file on webserver

What I am trying to do is create a small "shoutbox" where everyone will have a log on their computer that'll store everything that is typed over a textbox and upload it on a file that is located on a webserver. What I want it to do now is to overwrite existing content inside the file when file already exists.
The webserver is local.
What I've tried so far:
Private Sub sendmsg_Click(sender As Object, e As EventArgs) Handles sendmsg.Click
Try
Dim path As String = My.Computer.FileSystem.SpecialDirectories.MyDocuments & "\chatlog.txt"
Dim writer As StreamWriter = New StreamWriter(path, True)
Dim address As String = "http://localhost/tonakis2108/shoutbox.txt"
'Grabs text from textboxes and hides logfile
writer.WriteLine(nickname.Text + ": " + msg.Text)
writer.Close()
File.SetAttributes(path, FileAttributes.Hidden) 'Hides file
'Uploads file
My.Computer.Network.UploadFile(path, address, "", "", True, 50)
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
The problem:
The problem I face is when I change or delete the file on the server I get an error 404 that the destination doesn't exist and when the file is already there and empty it doesn't do anything when I upload.

"Open an existing file in Spreadsheetgear using VB.Net

I am trying to open an existing file in WorkBookView (named wkbMain in code given below) placed on my Windows Form. I am using the following code:
Private Sub MenuItemOpen_Click(sender As Object, e As EventArgs)
Dim lObjDialog As New OpenFileDialog
wkbMain.GetLock()
Try
If lObjDialog.ShowDialog() = DialogResult.OK Then
wkbMain = SpreadsheetGear.Factory.GetWorkbook(lObjDialog.FileName, System.Globalization.CultureInfo.CurrentCulture)
End If
Catch ex As Exception
Finally
wkbMain.ReleaseLock()
End Try
End Sub
But the assignment
wkbMain = SpreadsheetGear.Factory.GetWorkbook(lObjDialog.FileName, System.Globalization.CultureInfo.CurrentCulture)`)
throws an exception:
Unable to cast object of type 'ᢷ' to type 'SpreadsheetGear.Windows.Forms.WorkbookView'.
Please suggest a solution
You need to set the WorkbookView.ActiveWorkbook property to the object returned by Factory.GetWorkbook(...), not on your WorkbookView object itself. Example:
wkbMain.ActiveWorkbook = SpreadsheetGear.Factory.GetWorkbook(lObjDialog.FileName,
System.Globalization.CultureInfo.CurrentCulture))

Loaded file not generating in a listview - vb.net

I am trying to write a program that can load multiple different text files, containing encrypted values, individually to create a ListView of the encryptions is the first column and the decrypted value in the second column. The problem that I am running into is that when I load a file... nothing happens. There is no error, no crash, just nothing. I believe that it is not reading the file path correctly, but I am very new to this so that is only intuition. Here is my code:
Private Sub loadBtn_Click(sender As System.Object, e As System.EventArgs) Handles loadBtn.Click
valueList.Clear()
valueList.Columns.Add("Encypted File", 150)
valueList.Columns.Add("Decrypted", 100)
Dim newFile As New OpenFileDialog()
Try
If newFile.ShowDialog = Windows.Forms.DialogResult.OK Then
Dim writer As New System.IO.StreamReader(newFile.FileName)
Dim line() As String
Do Until writer.Peek <> -1
Dim newLine As ListViewItem
line = writer.ReadLine.Split("="c)
newLine.Text = line(0).ToString
valueList.Items.Add(newLine)
newLine.SubItems.Add(Crypto.AES_Decrypt(line(0)))
Loop
writer.Close()
End If
Catch ex As Exception
valueList.Items.Add("Error reading file." & ex.Message)
End Try
End Sub
There is a notification in the line
newLine.Text = line(0).ToString
that the variable 'newLine' is used before it has been assigned a value. I thought that I was assigning it a value at that time but I guess I am wrong. This does not cause a runtime error, just thought I should make not of it.