Creating text files not working - vb.net

This is probably a question that many of you have already seen a couple of times, but I'm really desperate since every solution i find on the internet doesn't work properly.
I want to create a simple .txt file. My code atm:
Public Class Form3
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
If TextBox1.Text = "" Then
MessageBox.Show("Your world needs a name")
Else
Dim file As System.IO.StreamWriter
file = My.Computer.FileSystem.OpenTextFileWriter("c:\test.txt", True)
file.WriteLine("Here is the first string.")
file.Close()
End If
End Sub
End Class
So as you can see, a file should be created when the button is pressed AND when there is text in the textbox.
Is the program not working or am searching the file in the wrong place? Thanks in avance!

Something like this may also be used:
Public Class Form3
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
If TextBox1.Text = "" Then
MessageBox.Show("Your world needs a name")
Else
Using file As New StreamWriter("c:\test.txt", True)
file.WriteLine("Here is the first string.")
file.Close()
End Using
End If
End Sub
End Class

Try this code
Public Class Form3
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
If TextBox1.Text = "" Then
MessageBox.Show("Your world needs a name")
Else
Dim file As System.IO.StreamWriter
file = My.Computer.FileSystem.OpenTextFileWriter(IO.Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), "test.txt"), True)
file.WriteLine("Here is the first string.")
file.Close()
End If
End Sub

Related

Saving and reading files on Visual basic

Hi I'm creating a "Toilet paper tracker" on visual basic and I'm struggling with saving and reading files, I know I am missing stuff. The user should be able to login and input a threshold and when reached a warning will pop up saying "buy more toilet paper" (i haven't coded this yet) and the user can add to create a total and subtract from it too. The user should also be able to save the total to a file and I want the program to be able to read the file and change the total if the user wants to add or subtract again. It would be greatly appreciated if you pointed me in the right direction, I'm only young so it's relatively simple. Here is my program :)
Imports System.IO
Public Class frmTPT
Private Sub TPT_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Call loadchangetotal()
End Sub
Sub loadchangetotal()
cboChange.Items.Add("Add to Total")
cboChange.Items.Add("Subtract from Total")
End Sub
Private Sub cboVenue_SelectedIndexChanged(sender As Object, e As EventArgs) Handles cboChange.SelectedIndexChanged
If cboChange.Text = "Add to Total" Then
Dim frmChangeACopy As New frmChangeA
frmChangeACopy.Show()
Me.Hide()
ElseIf cboChange.Text = "Subtract from Total" Then
Dim frmChangeSCopy As New frmChangeS
frmChangeSCopy.Show()
Me.Hide()
End If
End Sub
Private Sub btnReturn_Click(sender As Object, e As EventArgs)
Dim frmLoginCopy As New frmLogin
frmLoginCopy.Show()
Me.Hide()
End Sub
Private Sub btnClear_Click(sender As Object, e As EventArgs) Handles btnClear.Click
txtThreshold.Text = ""
cboChange.Text = ""
txtTotal.Text = ""
End Sub
Private Sub ExitToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles ExitToolStripMenuItem.Click
End
End Sub
Private Sub LogoutToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles LogoutToolStripMenuItem.Click
Dim frmLoginCopy As New frmLogin
frmLoginCopy.Show()
Me.Hide()
End Sub
Private Sub btnReadTotal_Click(sender As Object, e As EventArgs) Handles btnReadTotal.Click
Dim FileReader As StreamReader
Dim result As DialogResult
result = OpenFileDialog1.ShowDialog
If result = DialogResult.OK Then
FileReader = New StreamReader(OpenFileDialog1.Filename)
txtFileContent.Text = FileReader.ReadToEnd() 'i want to be able to read a
'previously saved total so that
FileReader.Close() 'it can be used to find the new total
'after it has been added to
End If 'or subtratced
End Sub
Private Sub SaveToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles SaveToolStripMenuItem.Click
Call SaveFile()
End Sub
Private Sub btnDisplay_Click(sender As Object, e As EventArgs) Handles btnDisplay.Click
Dim A, S, NewTotal As Integer
A = Val(frmChangeA.txtAdd.Text)
S = Val(frmChangeS.txtSubtract.Text)
NewTotal = A - S 'I want to be able to load a previously saved total if one exists and add and
'subtract from it
End Sub
End Class
Sub SaveFile()
Dim FileWriter As StreamWriter
Dim results As DialogResult
results = SaveFileDialog1.ShowDialog
If results = DialogResult.OK Then
FileWriter = New StreamWriter(SaveFileDialog1.FileName, False)
FileWriter.Write(txtFileContent.Text) ' is txtFileContent supposed to be
' the name of my textbox?
FileWriter.Close()
End If
End Sub
Design
You didn't mention if you were using .Net Core or 4.x. If the later, you can sometimes use the Insert Snippet functionality to learn how to do common tasks. For example in this case you could right click in the code editor and select Insert Snippet then Fundamentals then File System and finally Write text to a file. This will result in the following VB code:
My.Computer.FileSystem.WriteAllText("C:\Test.txt", "Text", True)
Unfortunately, this option doesn't work with .Net core since the My namespace wasn't ported to core.
The key point of this problem lies in reading and writing data from text. It is a clear idea to write two methods to achieve read and write.
You can refer to the following code. The two methods in the following example are WriteTotal(), ReadTotal().
Design:
Public Class Form1
Dim Oldtotal As Integer
Dim Newtotal As Integer
Private Sub btnLoadTotal_Click(sender As Object, e As EventArgs) Handles btnLoadTotal.Click
WriteTotal()
ReadTotal()
End Sub
Private Sub btnUpdateTotal_Click(sender As Object, e As EventArgs) Handles btnUpdateTotal.Click
cboChange.Text = Nothing
WriteTotal()
ReadTotal()
MsgBox("Inventory updated")
End Sub
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
cboChange.SelectedIndex = 0
ReadTotal()
End Sub
Sub WriteTotal()
Using swriter As IO.StreamWriter = New IO.StreamWriter("D:/paperstore.txt", False, System.Text.Encoding.UTF8)
If cboChange.Text = "Add to Total" Then
Newtotal = Oldtotal + CType(txtThreshold.Text, Integer)
swriter.WriteLine(Newtotal)
ElseIf cboChange.Text = "Subtract from Total" Then
If CType(txtThreshold.Text, Integer) > Oldtotal Then
swriter.WriteLine(Oldtotal)
MsgBox("buy more toilet paper")
Else
Newtotal = Oldtotal - CType(txtThreshold.Text, Integer)
swriter.WriteLine(Newtotal)
End If
Else
swriter.WriteLine(txtTotal.Text)
End If
End Using
End Sub
Sub ReadTotal()
Using sreader As IO.StreamReader = New IO.StreamReader("D:/paperstore.txt", System.Text.Encoding.UTF8)
Try
Oldtotal = sreader.ReadLine()
txtTotal.Text = Oldtotal
Catch ex As Exception
MsgBox(ex.Message)
End
End Try
End Using
End Sub
End Class

when the text in a textbox is equal to a certain word i need to value in the combo box to be saved for that text

I have orders in text files in the debug folder and when i type the name of the order in a text box it displays the order is a list box and there is a combo box underneath where i can change the status of the meal preparation (Being prepared, ready to deliver etc,). If i go back to that form and type in the same order name into the textbox i need to previous prepartion status to be already in the textbox. Thanks for any help!
Public Class frmOrderStatus
Private Sub btnStatus_Click(sender As Object, e As EventArgs) Handles btnStatus.Click
Dim sr As IO.StreamReader = IO.File.OpenText(strTxtOrderNum & ".txt")
Do Until sr.EndOfStream
lstOrder.Items.Add(sr.ReadLine)
Loop
End Sub
Private Sub OrderStatus_Load(sender As Object, e As EventArgs) Handles MyBase.Load
lstOrder.Items.Clear()
btnStatus.Enabled = False
ChangeStatus.Enabled = False
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles btnValidate.Click
strTxtOrderNum = txtOrderNum2.Text
btnStatus.Enabled = True
ChangeStatus.Enabled = True
End Sub
Private Sub Button1_Click_1(sender As Object, e As EventArgs) Handles Button1.Click
strSaveStatus = ChangeStatus.SelectedIndex
End Sub
Private Sub ChangeStatus_SelectedIndexChanged(sender As Object, e As EventArgs) Handles ChangeStatus.SelectedIndexChanged
End Sub
End Class
It recognizes the file; it just tells you it is in use. A Stream must be closed and disposed. I don't see the StreamReader even being closed let alone disposed. A `Using...End Using block will close and dispose of objects even if there is an error.
I just used a text file I happened to have to test.
Private strTxtOrderNum As String = "host"
Private Sub ReadFile()
Using sr As IO.StreamReader = IO.File.OpenText(strTxtOrderNum & ".txt")
Do Until sr.EndOfStream
ListBox1.Items.Add(sr.ReadLine)
Loop
End Using
End Sub
Private Sub WriteFile()
Dim strSelectedItem = ComboBox1.Text
Using swVar As IO.StreamWriter = IO.File.AppendText(strTxtOrderNum & ".txt")
swVar.WriteLine(strSelectedItem)
End Using
End Sub

VB.net Printform cant find path

So I am working on a form which need to be printed. I want to end up with a PDF file using Foxit PDF printer. The problem is that I cant figure out how to get the selected path as file location so I keep getting an the Path cannot be null.
error. Where in the code should I put my filelocation when using the Printform?
In this code the foldername is the location where I want to print.
Private Sub BtnPrint_Click(sender As Object, e As EventArgs) Handles BtnPrint.Click
Dim folderDlg As New FolderBrowserDialog
Dim foldername As String
folderDlg.ShowNewFolderButton = True
If (folderDlg.ShowDialog() = DialogResult.OK) Then
foldername = folderDlg.SelectedPath
Dim root As Environment.SpecialFolder = folderDlg.RootFolder
End If
PrintForm1.Print()
End Sub
Edit:
Actually deleted part of the code and still getting the same error (first part wasnt doing anything to start with I know that). All I am using now is:
Private Sub BtnPrint_Click(ByVal sender As System.Object, ByVal e As EventArgs) Handles BtnPrint.Click
PrintForm1.Print()
End Sub
Also microsoft help database about Printform isnt helping since I have done exactly what it says and still getting the Path is Null error
Edit 2:
So I am using this code now and it is working.
Private Sub BtnPrint_Click(ByVal sender As System.Object, ByVal e As EventArgs) Handles BtnPrint.Click
PrintDialog1.PrinterSettings = PrintForm1.PrinterSettings
PrintDialog1.AllowSomePages = True
If PrintDialog1.ShowDialog = DialogResult.OK Then PrintForm1.PrinterSettings = PrintDialog1.PrinterSettings
With Me.PrintForm1
.PrintAction = Printing.PrintAction.PrintToPreview
Dim MyMargins As New Margins
With MyMargins
.Left = 10
.Right = 10
.Top = 10
.Bottom = 10
End With
.PrinterSettings.DefaultPageSettings.Margins = MyMargins
.Print()
End With
End Sub
but as soon as I try to set which area it should print I get the following error: "Printing is not a member of powerpacks". I tried using the following code according to microsoft this is the way it should work.. I have no clue where the error comes from
.Print(Me, PowerPacks.Printing.PrintForm.PrintOption.ClientAreaOnly)
You don't need a path to use printform. Printform just prints what you see on the screen to your default printer. You need to install "Visual Basic PowerPacks" to use this command. More explanation you may find here:
https://learn.microsoft.com/en-us/dotnet/visual-basic/developing-apps/printing/how-to-print-a-form-by-using-the-printform-component
To preview your print you don't need to use printdialog and all this. You just click on printform1 in the designer,to get up the properties window of printform1. In printaction you choose PrintToPreview. Thats all its needed.
These are all the lines I need:
Public Class Form1
Private Sub Exit_Click(sender As Object, e As EventArgs) Handles Button2.Click
Application.Exit()
End Sub
Private Sub Print_Click(sender As Object, e As EventArgs) Handles Button1.Click
PrintForm1.Print()
End Sub
End Class

CreateText method produces error "The process cannot access the file because it is being used by another process"

I am working on a button that will delete text in gross.txt. I keep getting this error:
The process cannot access the file 'C:\Users\isaiah\Visual BASIC Programs\VB2012\Chap10\Gross Pay Solution\Gross Pay Project\bin\Debug\gross.txt' because it is being used by another process.
Or more specifically:
A first chance exception of type 'System.IO.IOException' occurred in mscorlib.dll.
It appears the error comes from btnDelete_Click at the bottom.
Option Explicit On
Option Strict On
Option Infer Off
Public Class frmMain
Private Sub btnExit_Click(sender As Object, e As EventArgs) Handles btnExit.Click
Me.Close()
End Sub
Private Sub txtGrossPay_KeyPress(sender As Object, e As KeyPressEventArgs) Handles txtGrossPay.KeyPress
' Allows the text box to accept only numbers, the period, and the Backspace key
If (e.KeyChar < "0" OrElse e.KeyChar > "9") AndAlso e.KeyChar <> "." AndAlso e.KeyChar <> ControlChars.Back Then
e.Handled = True
End If
End Sub
Private Sub btnSave_Click(sender As Object, e As EventArgs) Handles btnSave.Click
Dim outFile As IO.StreamWriter
outFile = IO.File.AppendText("gross.txt")
outFile.WriteLine(txtGrossPay.Text)
outFile.Close()
txtGrossPay.Text = ""
End Sub
Private Sub btnDisplay_Click(sender As Object, e As EventArgs) Handles btnDisplay.Click
' Declare new inFile Varable as a streamreader object
Dim inFile As IO.StreamReader
Dim dblLine As Double
' Opens gross.txt for input
inFile = IO.File.OpenText("gross.txt")
' .Exists() searches /bin folder for gross.txt, returns a boolean value
If IO.File.Exists("gross.txt") Then
inFile = IO.File.OpenText("gross.txt")
'Fill the list with the values
Do Until inFile.Peek = -1
Double.TryParse(inFile.ReadLine, dblLine)
lstContents.Items.Add(dblLine.ToString("C2").PadLeft(6, " "c))
Loop
Else
MessageBox.Show("The file you have requested does not exist", "Gross Pay Project",
MessageBoxButtons.OKCancel, MessageBoxIcon.Error)
End If
inFile.Close()
End Sub
Private Sub btnDelete_Click(sender As Object, e As EventArgs) Handles btnDelete.Click
Dim outDelete As IO.StreamWriter
outDelete = IO.File.CreateText("gross.txt")
outDelete.Close()
End Sub
End Class
Ok, I found the issue.
You were opening the file twice in your code with the line
inFile = IO.File.OpenText("gross.txt")
I commented out the first time you did it before your .Exists call. I also added a dispose to your Delete call. CreateText doesn't need to assign to anything so I commented out that code and added the line you needed. I tested and these changes fixed the issue. In fact the first change was the fix, the second one was just to clean things up.
Private Sub btnDisplay_Click(sender As Object, e As EventArgs) Handles btnDisplay.Click
'declare new inFile Varable as a streamreader object
Dim inFile As IO.StreamReader
Dim dblLine As Double
'opens gross.txt for input
' inFile = IO.File.OpenText("gross.txt")
'.Exists() searches /bin folder for gross.txt, returns a boolean value
If IO.File.Exists("gross.txt") Then
inFile = IO.File.OpenText("gross.txt")
'fill the list with the values
Do Until inFile.Peek = -1
Double.TryParse(inFile.ReadLine, dblLine)
lstContents.Items.Add(dblLine.ToString("C2").PadLeft(6, " "c))
Loop
inFile.Close()
Else
MessageBox.Show("The file you have requested does not exist", "Gross Pay Project",
MessageBoxButtons.OKCancel, MessageBoxIcon.Error)
End If
End Sub
Private Sub btnDelete_Click(sender As Object, e As EventArgs) Handles btnDelete.Click
'Dim outDelete As IO.StreamWriter
'outDelete = IO.File.CreateText("gross.txt")
'outDelete.Close()
IO.File.CreateText("gross.txt").Dispose
End Sub
I believe you need to call dispose ...
Private Sub btnDelete_Click(sender As Object, e As EventArgs) Handles btnDelete.Click
Dim outDelete As IO.StreamWriter
outDelete = IO.File.CreateText("gross.txt")
outDelete.Close()
outDelete.Dispose()
End Sub
Also in your Do Loop are you meaning to add a line when the
Double.TryParse(inFile.ReadLine, dblLine)
fails to parse? It seems like you would want to skip it if the parse fails
Do Until inFile.Peek = -1
if Double.TryParse(inFile.ReadLine, dblLine) then
lstContents.Items.Add(dblLine.ToString("C2").PadLeft(6, " "c))
end if
Loop
but up to you.
The error means what it says. Somewhere you have the file open. Perhaps in Notepad? Are you looking at the contents of the file perhaps?

Creating folders using vb.net

I'm starting on a program that creates a folder
this is what i currently have, now what i want to do is to have two textboxes, one textbox is for the directory and the other is for the folder name, how can i implement that here?
Private Sub CreateBTN_Click(sender As Object, e As EventArgs) Handles CreateBTN.Click
Dim Path As String = txttargerdirectory.Text
If Not Directory.Exists(Path) Then
Directory.CreateDirectory(Path)
MsgBox("folder created")
Else
MsgBox("Folder already exist")
End If
End Sub
Are you looking for something like this?
Private Sub CreateBTN_Click(sender As Object,
e As EventArgs) Handles CreateBTN.Click
Dim sPath As String = IO.Path.Combine(txtPath.Text, txtFolderName.Text)
If Not IO.Directory.Exists(sPath) Then
IO.Directory.CreateDirectory(sPath)
MsgBox("folder created")
Else
MsgBox("Folder already exist")
End If
End Sub