Loaded file not generating in a listview - vb.net - 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.

Related

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.

Avoid exiting a for/next on error

I should know better than to not give enough information/good information when asking for help. I have another question which I need to delete/link or merge here... any comment on how to do that would be great.
So the problem is I am trying to write a simple app (yeah, right) to locate a specific file on the local HDD. There WILL be multiple instances of the file (backups etc.) and I want to find each. Issues are that I cannot know how many local hdd there are and I cannot know what directory the file might be in.
So I wanted to
iterate through all fixed HDD
search the hdd for the file (I always know the name of the file)
I search HDD like this...
For Each drive As IO.DriveInfo In IO.DriveInfo.GetDrives
If drive.DriveType.ToString = "Fixed" Then
So if the found hdd is fixed I do this...
Try
For Each filename As String In IO.Directory.GetFiles(hdd, "user.config", IO.SearchOption.AllDirectories)
The issue is that I throw an exception, I have the for block above in a try catch, the exception is caught and the code exits.
OK, so I guess this is to be expected. Any suggestions on how to avoid this? Meaning I know I will run across files/directories I do not have permission for, how do I carry on and ignore what I don't care about?
FULL CODE LISTING
Private Sub Command1_Click(sender As System.Object, e As System.EventArgs) Handles Command1.Click
'variable to hold each hdd name eg: c:\
Dim hdd As String
Dim directories As Integer = 0
Dim files As Integer = 0
Try
For Each drive As IO.DriveInfo In IO.DriveInfo.GetDrives
If drive.DriveType.ToString = "Fixed" Then
'asign the variable hdd a name for this run through
hdd = drive.Name
'assign label value for directories
directories = directories + 1
Label6.Text = directories.ToString
Me.Refresh()
'search the hdd for the file user.config
Try
For Each filename As String In IO.Directory.GetFiles(hdd, "user.config", IO.SearchOption.AllDirectories)
Me.Refresh()
' 'assign label value for files
files = files + 1
Label2.Text = files.ToString
Me.Refresh()
' 'variable to hold the path for each found file
Dim file As String = IO.Path.GetFullPath(filename)
' 'update file checking label
Label4.Text = file.ToString
' 'add each found file to the list
List1.Items.Add(file)
Next
Catch ex As Exception
End Try
End If
Next
Catch ex As Exception
MsgBox(ex.ToString)
End Try
'iterate through each found drive
End Sub
You need to write it out long-wise because you need to handle the IO security issues. And of course a recursive function.
Called by:
FindFileOnAllDrivesOfType(System.IO.DriveType.Fixed, "test.txt")
Methods:
Public Function FindFileOnAllDrivesOfType(ByVal DriveType As System.IO.DriveType, ByVal FileToFind As String) As List(Of String)
Dim AllLocations As New List(Of String)
For Each drive As IO.DriveInfo In IO.DriveInfo.GetDrives
If drive.DriveType = DriveType Then
AllLocations = FindFile(drive.ToString(), FileToFind)
End If
Next
Return AllLocations
End Function
Public Function FindFile(ByVal StartDirectory As String, ByVal FileToFind As String) As List(Of String)
Dim AllLocations As New List(Of String)
Try
For Each dirname As String In IO.Directory.GetDirectories(StartDirectory)
AllLocations.AddRange(FindFile(dirname, FileToFind))
Next
For Each filename As String In IO.Directory.GetFiles(StartDirectory, FileToFind, IO.SearchOption.TopDirectoryOnly)
AllLocations.Add(filename)
Next
Catch ex As Exception
' MessageBox.Show(ex.Message)
'Do nothing as we can't get a directory listing
End Try
Return AllLocations
End Function

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.

Strange "IOException was unhandled"

(VB.NET, .NET 3.5)
I wrote the following function to read some text from txt file. It was working fine but now it's not. It keeps giving me this error message
"IOException was unhandled" and
" The process cannot access the file 'F:\kh_matt\ch1.txt' because it is being used by another process."
The ch1.txt is not even opened or being used by any program at all. I tried to move ch1.txt to another location (Drive D) still I got the same message error but just different location it says The process cannot access the file 'D:\ch1.txt' because it is being used by another process."
Here's my code block :
Private Sub btnRead_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnRead.Click
Dim reader As StreamReader
Dim filelocation As String
filelocation = "F:\kh_matt\ch1.txt"
Dim chid As Integer
chid = 1
If System.IO.File.Exists(filelocation) = True Then
reader = New StreamReader(New FileStream(filelocation, FileMode.Open))
Else
MsgBox(filelocation, MsgBoxStyle.OkOnly)
End If
Dim MyStream As New StreamReader(Path.Combine(Application.StartupPath, filelocation))
Dim vArray() As String = MyStream.ReadToEnd.Split(CChar("$"))
MyStream.Close()
Dim count As Integer
For d As Integer = 0 To vArray.Length - 1 Step 1
If d = vArray.Length - 1 Then
Exit For
End If
InsertKh(chid, d + 1, vArray(d))
count = d + 1
Next
MsgBox("Done Inserting")
End Sub
It always points to this code :
Dim MyStream As New StreamReader(Path.Combine(Application.StartupPath, filelocation))
Where I debug and press the respective button. Can anyone point out what the problem is ? Thanks
I think this is your problem:
If System.IO.File.Exists(filelocation) = True Then
reader = New StreamReader(New FileStream(filelocation, FileMode.Open))
If the file exists it will open a StreamReader on it, then try and open another StreamReader on the same file, which will lock the file, causing this line:
Dim MyStream As New StreamReader(Path.Combine(Application.StartupPath, filelocation))
to fail.
Also, some pointers:
consider using the System.IO.File.ReadAllText() method instead, much easier
if you must use streams, wrap them in a using block to ensure they're freed correctly, for example:
`
Dim vArray() As String
using (Dim MyStream As New StreamReader(Path.Combine(Application.StartupPath, filelocation))
{
vArray = MyStream.ReadToEnd.Split(CChar("$"))
}
(sorry if the above code isn't 100% correct, I don't write much VB.Net)
It seems you open the file twice, which is probably what's causing your error:
reader = New StreamReader(New FileStream(filelocation, FileMode.Open))
...
Dim MyStream As New StreamReader(Path.Combine(Application.StartupPath, filelocation))
Are you sure that's what you intend to do? It looks like you can remove MyStream and use reader instead. Also, you don't have to use Path.Combine, since filelocation is not relative.
Make sure that you close your stream & streamreader once you've finished reading the file, even when an exception is being thrown.
Use a try/finally block, and close the stream / streamreader in the finally block.
Thanks all for the reply. It's my mistake. I forgot to comment out my code that I wrote for testing earlier. After commenting this code out it works like before.
'If System.IO.File.Exists(filelocation) = True Then
' reader = New StreamReader(New FileStream(filelocation, FileMode.Open))
'Else
' MsgBox(filelocation, MsgBoxStyle.OkOnly)
'End If
Have a good day.