File.create shows no errors but doesnt create file? - vb.net

I'm trying to copy a file from an external drive by reading its contents, creating a new file elsewhere and writing the contents into it. My code shows no errors (using MSV) but when I try to 'download' the file, it completes the code but no file is created.
Can anyone help?
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
Dim FileReader As String
FileReader = My.Computer.FileSystem.ReadAllText(Label32.Text)
Dim fbd As FolderBrowserDialog = New FolderBrowserDialog
Dim DownloadLocation As String
If fbd.ShowDialog() <> DialogResult.Cancel Then
DownloadLocation = fbd.SelectedPath
File.Create(fbd.SelectedPath & "pandora speedsign log.txt").Dispose()
File.WriteAllText(fbd.SelectedPath & "pandora speedsign log.txt", FileReader)
MessageBox.Show("success!!")
End If
'File.Create("C:\Users\%UserProfile%\Downloads" & DownloadFileDate & ".txt")
'File.WriteAllText("C:\Users\%USERPROFILE%\Downloads" & DownloadFileDate & ".txt", FileReader)
End Sub
I've been looking for different ways of creating the file, different ways of writing the file but nothing seems to work.

We can significantly simplify the code like this:
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
Dim fbd As New FolderBrowserDialog()
If fbd.ShowDialog() <> DialogResult.Ok Then Exit Sub
Dim outputPath As String = IO.Path.Combine(fbd.SelectedPath, "pandora speedsign log.txt")
IO.File.Copy(Label32.Text, outputPath)
End Sub

Related

VB.NET How to copy the application's executable file to another path?

I'm new to VB.NET and I'm trying to experiment with it. So when the user clicks a button from the application, the executable file should copy itself to a specific path.
So, how can I do that?
Thanks.
This is not recommended but possible - think about why in the earth you want to do that. A software is not just an EXE.
Public Class Form1
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim FileToCopy As String
Dim NewCopy As String
FileToCopy = Application.StartupPath.ToString & "\WindowsApplication1.exe"
NewCopy = "D:\_working\WindowsApplication1.exe.copied"
If System.IO.File.Exists(FileToCopy) = True Then
System.IO.File.Copy(FileToCopy, NewCopy)
MessageBox.Show("File Copied")
End If
End Sub
End Class
The code above is flawed if you are speaking about getting your own assembly in Visual Studios to copy itself to a given path. I tested the following code and it worked without error. Please note the path will have to be changed to fit your needs and be sure to use the name of your program, mine was CryLok.exe.
Reference: https://learn.microsoft.com/en-us/dotnet/api/system.reflection.assembly.location?view=net-5.0
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim FileToCopy As String
Dim NewCopy As String
FileToCopy = Reflection.Assembly.GetExecutingAssembly().Location
NewCopy = "C:\Users\your name\Desktop\CryLok.exe"
If File.Exists(FileToCopy) = True Then
File.Copy(FileToCopy, NewCopy)
MessageBox.Show("File Copied")
End If
End Sub

How to get program to write a new line in sequential access file instead of deleting it?

I'm trying to write to a sequential access file, but everytime I click the write button, the first listbox selection is deleted from the file and the new one is added, how do I fix this?
Private Sub MainForm_Load(sender As Object, e As EventArgs) Handles Me.Load
'fills list box with parties
partyListBox.Items.Add("Democrat")
partyListBox.Items.Add("Republican")
partyListBox.Items.Add("Independent")
End Sub
Private Sub writeButton_Click(sender As Object, e As EventArgs) Handles writeButton.Click
Dim outFile As IO.StreamWriter
Dim party As String = partyListBox.SelectedItem.ToString
Dim age As Integer
Integer.TryParse(ageTextBox.Text, age)
outFile = IO.File.CreateText("politicalparties.txt")
'write to file
outFile.WriteLine(party & ", " & age)
'close file
outFile.Close()
End Sub
You can do the following to append a line of text to the end of the file:
Using sw As StreamWriter = File.AppendText("politicalparties.txt")
sw.WriteLine(party & ", " & age)
End Using
If the file does not yet exist, it will be created.

Open only files with *.bin

It is possible to add open only files with *.bin extension in openfile dialog ?
Here is my code. Maybe somebody can fix it.
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim OFD As New OpenFileDialog
Dim fullFile() As Byte
If OFD.ShowDialog = Windows.Forms.DialogResult.OK Then
fullFile = File.ReadAllBytes(OFD.FileName)
TextBox1.AppendText(fullFile(&H1E).ToString("X2") & " ")
TextBox1.AppendText(fullFile(&H1F).ToString("X2"))
End If
If file have another extension msg,box : Wrong file
You need to use the Filter property: MSDN
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim OFD As New OpenFileDialog
OFD.Filter = "BIN Files (*.bin)|*.bin"
Dim fullFile() As Byte
If OFD.ShowDialog = Windows.Forms.DialogResult.OK Then
fullFile = File.ReadAllBytes(OFD.FileName)
TextBox1.AppendText(fullFile(&H1E).ToString("X2") & " ")
TextBox1.AppendText(fullFile(&H1F).ToString("X2"))
End If
End Sub
The pipe | character is used in the filter string to separate it into chunks: the first is what the user sees in the dropdown, and the second is the actual filter that is run on the files. You can have multiple filters available, too. Here's another example of a filter string: Text files (*.txt)|*.txt|All files (*.*)|*.*
You need to use javax.swing.JFileChooser.
Use this:
FileNameExtensionFilter filter = new FileNameExtensionFilter("Binary Files", "bin");
JFileChooser fileChooser = new JFileChooser();
fileChooser.setFileFilter(filter);

How to save data within the Application?

I'm creating a basic To-do program. I want to save the list of tasks the user creates. Now I've tried with saving them as text files but I don't want it that way. I want it so that I can save the tasks the user creates within the program rather than external text files and then retrieve those saved files and display them in a text file.
Essentially I need a way to save data without needing to rely on databases.
A good example is GeeTeeDee. It seems to be saving its files and data etc. in the program within rather than external text file.(I'm assuming this because I can't seem find them. I could be wrong)
Update
I was doing a bit of searching can came across this: Click here!!!
But the problem is that I'm confused as to how this works. Is someone able to clear things for me? It would be GREATLY appreciated as it's exactly what I'm looking for.
The "code project" example saves the data at an external file with extension [*.brd] .
You can Use XmlSerializer to save and load your data from external xml file with extension xml,brd or anything else.
Try the code below, add into a form1 three buttons (Button1,Button2,Button3) and a DataGridView1, paste the code and Run.
press button "add data dynamically" or/and add,edit,delete row directlly from DataGridView1.
press Save data.
close and run programm
press Load data.
Imports System.Xml.Serialization
Imports System.IO
Class Form1
Dim ds As DataSet
Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
Button1.Text = "Load Data"
Button2.Text = "add data dynamically"
Button3.Text = "Save Data"
'Create Dataset
ds = CreateDataset()
'Set DataGridView1
DataGridView1.DataSource = ds.Tables("Person")
End Sub
Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
LoadFromXMLfile("c:\temp\persons.xml")
End Sub
Private Sub Button2_Click(sender As System.Object, e As System.EventArgs) Handles Button2.Click
AddDataToDataSetDynamically(ds)
End Sub
Private Sub Button3_Click_1(sender As System.Object, e As System.EventArgs) Handles Button3.Click
SaveToXMLFile("c:\temp\persons.xml", ds)
End Sub
Private Function CreateDataset() As DataSet
Dim dataset1 As New DataSet("Persons")
Dim table1 As New DataTable("Person")
table1.Columns.Add("Id")
table1.Columns.Add("FName")
table1.Columns.Add("Age")
'...
dataset1.Tables.Add(table1)
Return dataset1
End Function
Private Sub AddDataToDataSetDynamically(d As DataSet)
d.Tables("Person").Rows.Add(1, "Andrew", "46")
d.Tables("Person").Rows.Add(2, "Nicky", "43")
d.Tables("Person").Rows.Add(3, "Helen", "15")
End Sub
Private Sub SaveToXMLFile(filename As String, d As DataSet)
Dim ser As XmlSerializer = New XmlSerializer(GetType(DataSet))
Dim writer As TextWriter = New StreamWriter(filename)
ser.Serialize(writer, d)
writer.Close()
End Sub
Private Sub LoadFromXMLfile(filename As String)
If System.IO.File.Exists(filename) Then
Dim xmlSerializer As XmlSerializer = New XmlSerializer(ds.GetType)
Dim readStream As FileStream = New FileStream(filename, FileMode.Open)
ds = CType(xmlSerializer.Deserialize(readStream), DataSet)
readStream.Close()
DataGridView1.DataSource = ds.Tables("Person")
Else
MsgBox("file not found! add data and press save button first.", MsgBoxStyle.Exclamation, "")
End If
End Sub
End Class
add that code to form1 and get the data to a textbox (add button4,textbox1)
Private Function PrintRows(dataSet As DataSet) As String
Dim s As String = ""
Dim thisTable As DataTable
For Each thisTable In dataSet.Tables
Dim row As DataRow
For Each row In thisTable.Rows
Dim column As DataColumn
For Each column In thisTable.Columns
s &= row(column) & " "
Next column
s &= vbCrLf
Next row
Next thisTable
Return s
End Function
Private Sub Button4_Click(sender As System.Object, e As System.EventArgs) Handles Button4.Click
TextBox1.Text = PrintRows(ds)
End Sub

Save Data to text tile using SaveFileDialog?

I have already viewed the MSDN Example but I am still having problems.
I created a super-simple program to multiply two numbers, and display the output in the textbox. Now I need to be able to read that text box value and put the value in a text file, bringing up the save to file dialog when the "Save To File" button is clicked.
Private Sub MutiplyBtn_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MutiplyBtn.Click
Dim FirstNum As Double = Num1.Text
Dim SecondNum As Double = Num2.Text
Dim Answer2 As Double = FirstNum * SecondNum
Answerbox.Text = Answer2
End Sub
Private Sub SaveResultToFile_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles SaveResultToFile.Click
Dim myStream As Stream
Dim saveFileDialog1 As New SaveFileDialog()
saveFileDialog1.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*"
saveFileDialog1.FilterIndex = 2
saveFileDialog1.RestoreDirectory = True
If saveFileDialog1.ShowDialog() = DialogResult.OK Then
myStream = saveFileDialog1.OpenFile()
If (myStream IsNot Nothing) Then
System.IO.File.WriteAllText(Answerbox.Text)
myStream.Close()
End If
End If
End Sub
Currently, Visual Studio is giving me an error: Overload resolution failed because no accessible 'WriteAllText' accepts this number of arguments.
WriteAllText static method requires the name of the file where the data should be written to.
You could use directly the name selected in the saveFileDialog1
If saveFileDialog1.ShowDialog() = DialogResult.OK Then
System.IO.File.WriteAllText(saveFiledialog1.FileName, Answerbox.Text)
End If
instead if you really want to use the stream opened by OpenFile() method your code should be
If saveFileDialog1.ShowDialog() = DialogResult.OK Then
Dim sw As StreamWriter = new StreamWriter(saveFileDialog1.OpenFile())
If (sw IsNot Nothing) Then
sw.WriteLine(Answerbox.Text)
sw.Close()
End If
End If
The code is an example, you need to add a bit of error handling
Hi I tried above method but I succeed in this way....
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
SaveFileDialog1.Filter = "TXT Files (*.txt*)|*.txt"
If SaveFileDialog1.ShowDialog = Windows.Forms.DialogResult.OK _
Then
My.Computer.FileSystem.WriteAllText _
(SaveFileDialog1.FileName, RichTextBox1.Text, True)
End If
End Sub