Uploadfile method to overwrite file on webserver - vb.net

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.

Related

vb.net cannot find file after file has been deleted and resaved by remote pc

I'm using a web page to create a file on a web server to control an Arduino device. The file gets created without issue. The problem exists when the VB app that controls the Arduino device reads the file and then deletes the file. After VB deletes the file the web app recreates the same file with new data. The VB app fails to see the new file. It still thinks the file has been deleted.
Here's the code:
Private Sub TimerCheck4CameraFile_Tick(sender As Object, e As EventArgs) Handles TimerCheck4CameraFile.Tick
Try
' Check if file exists if it doesn't leave this method.
Dim DirectoryList As New IO.DirectoryInfo("C:\inetpub\wwwroot")
Dim ArrayOfFilesFileInfo As IO.FileInfo() = DirectoryList.GetFiles("ServoDirection2Move.txt")
Dim Fi As IO.FileInfo
For Each Fi In ArrayOfFilesFileInfo
If String.Compare("ServoDirection2Move.txt", Fi.Name) <> 0 Then
TextBox1.Text += vbCrLf + "Did NOT Find File."
Exit Sub ' We DID NOT find the file so get out!
End If
Next
Catch ex As Exception
LabelStatus.Text = "Catch ex 1: " + ex.Message
End Try
' Read in the file.
Dim FileRead As String
Try
' **POSSIBLE ISSUE HERE**.
FileRead = My.Computer.FileSystem.ReadAllText("C:\inetpub\wwwroot\ServoDirection2Move.txt")
' Need better way to read txt file. It fails after file is deleted and can not read second file.
TextBox1.Text += vbCrLf + "Moving Value: " + FileRead
Catch ex As Exception
LabelStatus.Text = "Catch ex: " + ex.Message
End Try
' Check if it was UP.
If String.Compare("UP", FileRead) = 0 Then
' Delete the file to prepare for a new one.
System.IO.File.Delete("C:\inetpub\wwwroot\ServoDirection2Move.txt")
' Move servo to proper location.
Call PanningUp.PerformClick()
LabelStatus.Text = "Done Moving: UP" ' Update Status Bar.
TimerCheck4CameraFile.Enabled = True ' Turn timer back on.
Exit Sub
End If

ftp download stopping before end of list

I'm using the following code to download files from an FTP server. Before entering this code, I have created a list of filenames from files that are in the directory on the FTP server. There are over 2000 files in the list.
As I iterate through the list, the files download properly until I reach exactly 121 files downloaded. Then it starts giving me an error of "file not found, access denied." for every file after that. However the files are there. If I start the process over again it will pick up from where it left off and download another 121 files and continue until it errors again after the next 121 files.
Here is the code:
For Each file As String In dirlist
DownloadFile(local_path + "\" + filename, new_path + "/" + Trim(filename), client)
Next
Private Sub DownloadFile(ByVal localpath As String, ByVal ftpuri As String, client As String)
Dim request As New WebClient()
request.Credentials = New NetworkCredential(user_name, password)
Dim bytes() As Byte = request.DownloadData(ftpuri)
Try
Dim DownloadStream As FileStream = IO.File.Create(localpath)
DownloadStream.Write(bytes, 0, bytes.Length)
DownloadStream.Close()
Catch ex As Exception
add_to_log(log_window, ex.Message)
End Try
End Sub
I do not understand why it is stopping before completing the list.

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.

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.

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.