Is It Possible To Create a Custom File Type For a Program In VB - vb.net

Is it possible to have a custom file type that would open in a VB program.
For example: There is a text box with some text and a check box that's checked... You would save to a custom file type and when you opened the file up again, the check box would be checked and the text box would have the text. It would basically save the state of the program to a custom file type.
E.g. -> .pro, .lll, .hgy, .xyz, .abc
I'm just curious... is this possible and if so, how would I approach this?

You can do what Ichiru states with a BinaryWriter and BinaryReader which I have done with some of my projects before using an in Memory datatable and serializing it.
Imports System.IO
Public Class Form1
Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
Using bs As New BinaryWriter(File.Open("Mydata.xyz", FileMode.Create))
bs.Write(TextBox1.Text)
bs.Write(CheckBox1.Checked)
bs.Close()
End Using
End Sub
Public Sub New()
' This call is required by the designer.
InitializeComponent()
' Add any initialization after the InitializeComponent() call.
If File.Exists("Mydata.xyz") Then
Using br As New BinaryReader(File.Open("Mydata.xyz", FileMode.Open))
Try
TextBox1.Text = br.ReadString
CheckBox1.Checked = br.ReadBoolean
Catch ex As EndOfStreamException
'Catch any errors because file is incomplete
End Try
End Using
End If
End Sub
End Class
But .Net has a built in Settings Class that you can use to persist your Data. It would be used like this
Public Class Form1
Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
My.MySettings.Default.checkbox1 = CheckBox1.Checked
My.MySettings.Default.textbox1 = TextBox1.Text
My.MySettings.Default.Save()
End Sub
Public Sub New()
' This call is required by the designer.
InitializeComponent()
' Add any initialization after the InitializeComponent() call.
CheckBox1.Checked = My.MySettings.Default.checkbox1
TextBox1.Text = My.MySettings.Default.textbox1
End Sub
End Class

Yes, it is possible to create your own custom filetype.
The best way to go around this kind of problem is to create a Binary Writer
In the binary writer you would write the contents of the textbox, and the state of the checkbox.
Writing:
BinaryWriter.Write("string")
BinaryWriter.Write(false)
Reading:
String str
Boolean bool
str = BinaryReader.ReadString()
bool = BinaryReader.ReadBoolean()

This is not possible unless you have your system's default application setup to open with your executable that will read this custom-extension data file.
Custom extensions can't be executed like a .exe would be, but they can be read by a .exe and used to configure settings for that particular .exe

Related

Could someone explain where are the errors in this code in vb.net

I'm new to this site and also a newbee in vb.net, I created a simple form in vb.net, a form with 3 buttons, by clicking Button1 Species1.txt is created, and by clicking Button2 the lines in Species1.txt are copied in a String Array called astSpecies(), and by Button3 the String Array is copied in a new file, named Species2.txt, below is the code.
Public Class Form4
Dim astSpecies() As String
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim myStreamWriter = New StreamWriter("C:\Users\Administrator\Documents\species1.txt", True)
myStreamWriter.WriteLine("Pagasius pangasius")
myStreamWriter.WriteLine("Meretrix lyrata")
myStreamWriter.WriteLine("Psetta maxima")
myStreamWriter.WriteLine("Nephrops norvegicus")
myStreamWriter.WriteLine("Homarus americanus")
myStreamWriter.WriteLine("Procambarus clarkii")
myStreamWriter.Close()
MsgBox("list complete")
End Sub
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
Dim myStreamReader = New StreamReader("C:\Users\Administrator\Documents\species1.txt")
Dim i As Integer
Dim stOutput As String
stOutput = ""
Do While Not myStreamReader.EndOfStream
astSpecies(i) = myStreamReader.ReadLine
stOutput = stOutput & astSpecies(i) & vbNewLine
i = i + 1
Loop
myStreamReader.Close()
MsgBox(stOutput)
End Sub
Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click
Dim myStreamWriter = New StreamWriter("C:\Users\Administrator\Documents\species2.txt", True)
Dim o As Integer
Do While o <= astSpecies.Length
myStreamWriter.WriteLine(astSpecies(o))
o = o + 1
Loop
myStreamWriter.Close()
End Sub
End Class
First of all, you should make a few settings when it comes to VB.Net. 1.) set Option Strict to On 2.) remove the VB6 namespace. VB6 is the old Visual Basic. There are many functions in this that are inefficient from today's perspective. So please do not write MsgBox() but MessageBox.Show("").
(If you still need control characters such as NewLine or Tab, you can set a selective reference with Imports Microsoft.VisualBasic.ControlChars. Sounds contradictory, but it is useful, because why should you also write ChrW(9), it is not legible.)
I quickly started a project myself and wrote whatever you wanted.
I still don't quite understand why you first write things into a text file, then read them out, and then write that into a second text file – I want to say: where do the strings originally come from? The strings must have been there already? Anyway, I filled a List(of String) in the Button2_Click procedure. This has the advantage that you don't have to know in advance how many strings are coming, and you can sort them later and so on ...
You should also discard all Writers when you no longer need them. So use Using. Otherwise it can happen that the written files are not discarded and you can no longer edit the file.
Imports Microsoft.VisualBasic.ControlChars
Imports Microsoft.WindowsAPICodePack.Dialogs
Public NotInheritable Class FormMain
Private Path As String = ""
Private allLines As New List(Of String)
Private Sub FormMain_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Me.BackColor = Color.FromArgb(161, 181, 165)
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Using OFolderD As New CommonOpenFileDialog
OFolderD.Title = "Ordner auswählen"
OFolderD.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.Desktop)
OFolderD.IsFolderPicker = True
If OFolderD.ShowDialog() = CommonFileDialogResult.Ok Then
Path = OFolderD.FileName
Else
Return
End If
End Using
Path &= "\Data.txt"
Using txtfile As System.IO.StreamWriter = My.Computer.FileSystem.OpenTextFileWriter(Path, True)
txtfile.WriteLine("Pagasius pangasius")
txtfile.WriteLine("Meretrix lyrata")
txtfile.WriteLine("Psetta maxima")
txtfile.WriteLine("Nephrops norvegicus")
txtfile.WriteLine("Homarus americanus")
txtfile.WriteLine("Procambarus clarkii")
txtfile.Close()
End Using
End Sub
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
'read all Text
Dim RAT() As String = System.IO.File.ReadAllLines(Path, System.Text.Encoding.UTF8)
If RAT.Length = 0 OrElse RAT.Length = 1 Then
MessageBox.Show("The File only contains 0 or 1 characters.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Hand)
Return
End If
allLines.AddRange(RAT)
End Sub
Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click
Dim Pfad_txt As String = Path.Substring(0, Path.LastIndexOf("\"c)) & "\Data2.txt"
Using txtfile As System.IO.StreamWriter = My.Computer.FileSystem.OpenTextFileWriter(Pfad_txt, True)
For Each Line As String In allLines
txtfile.WriteLine(Line)
Next
txtfile.Close()
End Using
End Sub
End Class
By the way: I use a FolderBrowserDialog in the Button1_Click procedure. This should be done so that the program also runs properly on other PCs. In order to be able to use the FBD, you have to download Microsoft.WindowsAPICodePack.Dialogs in Visual Studio's own Nuget package manager.
how to set Option Strict to On
How to uncheck VB6.
how to install FolderBrowserDialog in Visual Studio
Button1
If you want to use a StreamWriter it should be disposed. Classes in the .net Framework that have a Dispose method may use resources outside of the framework which need to be cleaned up. The classes shield you from these details by provided a Dispose method which must be called to properly do the clean up. Normally this is done with Using blocks.
I used a string builder which saves creating and throwing away a string each time you change the string. You may have heard that strings are immutable (cannot be changed). The StringBuilder class gets around this limitation. It is worth using if you have many changes to your string.
The File class is a .net class that you can use to read or write files. It is not as flexible as the stream classes but it is very easy to use.
Button 2
When you declared your Array, you declared an array with no elements. You cannot add elements to an array with no space for them. As Daniel pointed out, you can use the .net class List(Of T) The T stands for Type. This is very good suggestion when you don't know the number of elements in advance. I stuck with the array idea by assigning the array returned by File.ReadAllLines to the lines variable.
You get the same result by simply reading all the text and displaying it.
Button 3
Again I used the File class here which allows you to complete your task in a single line of code. Using 2 parameters for the String.Join method, the separator string and the array to join, we reproduce the original file.
Private SpeciesPath As String = "C:\Users\maryo\Documents\species1.txt"
Private lines As String()
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim sb As New StringBuilder
sb.AppendLine("Pagasius pangasius")
sb.AppendLine("Meretrix lyrata")
sb.AppendLine("Psetta maxima")
sb.AppendLine("Nephrops norvegicus")
sb.AppendLine("Homarus americanus")
sb.AppendLine("Procambarus clarkii")
File.WriteAllText(SpeciesPath, sb.ToString)
MsgBox("list complete")
End Sub
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
lines = File.ReadAllLines(SpeciesPath)
MessageBox.Show(String.Join(Environment.NewLine, lines))
'OR
MessageBox.Show(File.ReadAllText(SpeciesPath))
End Sub
Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click
File.WriteAllLines("C:\Users\maryo\Documents\species2.txt", lines))
End Sub

Get fileName into Textbox before Loading Form1

I have a problem with Drag and Drop file Code, I try many methods but I failed this is my Code.
Module Module1
Sub Main(ByVal args() As String)
Dim pathstring As String
If args.Length > 0 Then
Dim path = args(0)
pathstring = path
End If
End Sub
End Module
Public Class Form1
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
TextBox1.Text = pathstring
End Sub
End Class
Above Code working fine with Console Application, but not in WindowsApplication
I want to get filename into Textbox1 Control before loading Form.
You need to learn how WinForms apps work. That Main method isn't even being executed because it's not the entry point for the app. Unless you disable the Application Framework, you need to handle the app's Startup event if you want to do something before creating the startup form. That said, you can get the commandline arguments anywhere, any time by calling Environment.GetCommandLineArgs.

Use running instance to execute commandline in vb.net

I'd like to use a running instance of my application (a single instance application) to run a new commandline...
I've heard about mutexes and IPC mechanisms but I don't know how to use it.
Explanation :
Public Class Form1
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
MsgBox(Environment.CommandLine)
End Sub
End Class
Example :
I launch the app with a file as argument, it shows the MsgBox and I let it run. If I launch once again the app with a file as argument, it won't show the MsgBox...
How can I show it with the new commandline ?
Regards, Drarig29.
In VB.NET you can make your application single instance from the project properties page. Check the "Make single instance application" option, then click the "View Application Events" button:
In the ApplicationEvents.vb class, add a handler for StartupNextInstance - this will be called when the application is already running and you start it again. You can call a method on your main form:
Namespace My
Partial Friend Class MyApplication
Private Sub MyApplication_StartupNextInstance(sender As Object, e As ApplicationServices.StartupNextInstanceEventArgs) Handles Me.StartupNextInstance
' Handle arguments when app is already running
If e.CommandLine.Count > 0 Then
' Pass the argument to the main form
Dim form = TryCast(My.Application.MainForm, Form1)
form.LoadFile(e.CommandLine(0))
End If
End Sub
End Class
End Namespace
In your main form, you can pass the initial command line arguments, and handle the subsequent ones, with a common method:
Public Class Form1
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles Me.Load
' Handle arguments from the initial launch
Dim args = Environment.GetCommandLineArgs()
If args.Length > 1 Then
LoadFile(args(1))
End If
End Sub
Public Sub LoadFile(filename As String)
MessageBox.Show(filename)
End Sub
End Class

Is there a way to get the input from a Load event handler (entered via inputBox) to be used Globally in the program?

I am creating a form that will prompt the user to enter a file name upon loading the file. The issue I encounter is that my variable I use to store the input is not recognized in another one of my procedures. The code here shows my current set up.
Imports System.IO
Public Class frmEmployee
Sub frmEmployee_load(ByVal sender As Object, e As System.EventArgs)
Dim strFileName = InputBox("Please name the file you would like to save the data to: ")
End Sub
Private Sub btnClear_Click(sender As Object, e As EventArgs) Handles btnClear.Click
txtEmail.Clear()
txtExtension.Clear()
txtFirst.Clear()
txtLast.Clear()
txtMiddle.Clear()
txtNumber.Clear()
txtPhone.Clear()
End Sub
Private Sub btnSave_Click(sender As Object, e As EventArgs) Handles btnSave.Click
Dim inputFile As New StreamWriter(strFileName)
If File.Exists(strFileName) = True Then
inputFile = File.CreateText(strFileName)
inputFile.Write(txtEmail.Text)
inputFile.Write(txtExtension.Text)
inputFile.Write(txtFirst.Text)
inputFile.Write(txtLast.Text)
inputFile.Write(txtMiddle.Text)
inputFile.Write(txtNumber.Text)
inputFile.Write(txtPhone.Text)
inputFile.Write(cmbDepart.Text)
Else
MessageBox.Show("" & strFileName & "Cannot be created or found.")
End If
End Sub
Private Sub btnExit_Click(sender As Object, e As EventArgs) Handles btnExit.Click
Me.Close()
End Sub
End Class
The load event handler is where I want the user to input the name of the file.
Change the scope of your variable to outside of your load method...
Public Class frmEmployee
Private strFileName As String
Sub frmEmployee_load(ByVal sender As Object, e As System.EventArgs)
strFileName = InputBox("Please name the file you would like to save the data to: ")
End Sub
You could use My.Settings and load the file string there and save it. All forms can now access that. When you close the the app set it to String.Empty if you want it to be.
You also could be taking advantage of a class object for the fields you are capturing then using either BinaryFormatter or XmlSerializer to store the data. Better databinding, creation and reconstruction using an object.
My.Settings.Filename = Inputbox("Filename?")
My.Settings.Save()
The problem with the approach you have there is that your variabl strFileName is scoped to the class frmEmployee.
You need to set up a genuinely global variable (at the application startup) an then use that. So you will need a Sub Main as an entry point to your application See here, and just before that create a public variable to hole the file name.
So you might have something like this for your application startup:
Public fileNametoUse as string
Public Sub Main()
Application.EnableVisualStyles()
Application.SetCompatibleTextRenderingDefault(False)
Application.Run(New Form1)
End Sub
Then in you load sub for frmEmployee you would have:
fileNametoUse = InputBox("Please name the file you would like to save the data to: ")

Pressing a button in visual basic

I am new to Visual Basic.NET and I am just playing around with it. I have a book that tells me how to read from a file but not how to write to the file with a button click. All I have is a button and a textbox named fullNameBox. When I click the button it gives me an unhandled exception error. Here is my code:
Public Class Form1
Sub outputFile()
Dim oWrite As System.IO.StreamWriter
oWrite = System.IO.File.CreateText("C:\sample.txt")
oWrite.WriteLine(fullNameBox.Text)
End Sub
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
outputFile()
End Sub
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
End Sub
End Class
Have you tried stepping through your application to see where the error is? With a quick glance, it looks like you might need to use System.IO.File on the fourth line (oWrite = IO.File...) instead of just IO, but I haven't tried to run it.
Imports System.IO
Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
SaveFileDialog1.FileName = ""
SaveFileDialog1.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*"
SaveFileDialog1.ShowDialog()
If SaveFileDialog1.FileName.Trim.Length <> 0 Then
Dim fs As New FileStream(SaveFileDialog1.FileName.Trim, FileMode.Create)
Dim sr As New StreamWriter(fs)
sr.Write(TextBox1.Text)
fs.Flush()
sr.Close()
fs.Close()
End If
End Sub
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
OpenFileDialog1.FileName = ""
OpenFileDialog1.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*"
OpenFileDialog1.ShowDialog()
If OpenFileDialog1.FileName.Trim.Length <> 0 Then
Dim fs As New FileStream(OpenFileDialog1.FileName.Trim, FileMode.Open)
Dim sw As New StreamReader(fs)
TextBox1.Text = sw.ReadToEnd
fs.Flush()
sw.Close()
fs.Close()
End If
End Sub
End Class
this is a complete functional program if you want, you just need to drag drop a textbox, openfiledialog, and a savefiledialog.
feel free to play around with the code.
enjoy
by the way, the problem in your code is that you "must" close filestream when your done using it, doing so will release any resource such as sockets and file handles.
The .net framework is a very powerful framework. In the same way (however) it has easy and convenient methods for simple tasks. Most individuals tend to complicate things in order to display knowledge. But less code = less processing = faster and more efficient application (sometimes) so the large above method may not be suitable. Along with that, the above mentioned method would be better off written as a sub or if returning something then a function.
My.Computer.FileSystem.WriteAllText("File As String", "TextAsString", Append as Boolean)
A general Example would be
My.Computer.FileSystem.WriteAllText("C:\text.text", "this is what I would like to add", False)
this is what I would like to add
can be changed to the current text of a field as well.
so a more specific example would be
My.Computer.FileSystem.WriteAllText("C:\text.text", fullNameBox.text, True)
If you would like to understand the append part of the code
By setting append = true you are allowing your application to write the text at the end of file, leaving the rest of the text already in the file intact.
By setting append = false you will be removing and replacing all the text in the existing file with the new text
If you don't feel like writing that part of the code (though it is small) you could create a sub to handle it, however that method would be slightly different, just for etiquette. functionality would remain similar. (Using StreamWriter)
Private Sub WriteText()
Dim objWriter As New System.IO.StreamWriter("file.txt", append as boolean)
objWriter.WriteLine(textboxname.Text)
objWriter.Close()
End Sub
The Specific Example would be
Private Sub WriteText()
Dim objWriter As New System.IO.StreamWriter("file.txt", False)
objWriter.WriteLine(fullnamebox.Text)
objWriter.Close()
End Sub
then under the button_click event call:
writetext()
You can take this a step further as well. If you would like to create a more advabced Sub to handle any textbox and file.
Lets say you plan on having multiple separate files and multiple fields for each file (though there is a MUCH cleaner more elegant method) you could create a function. {i'll explain the concept behind the function as thoroughly as possible for this example}
below is a more advanced sub demonstration for your above request
Private Sub WriteText(Filename As String, app As Boolean, text As String)
Dim objWriter As New System.IO.StreamWriter(Filename, app)
objWriter.WriteLine(text)
objWriter.Close()
End Sub
What this does is allows us to (on the same form - if you need it global we can discuss that another time, it's not much more complex at all) call the function and input the information as needed.
Sub Use -> General Sample
WriteText(Filename As String, app As Boolean)
Sub Use -> Specific Sample
WriteText("C:\text.txt, False, fullnamebox.text)
But the best part about this method is you can change that to be anything as you need it.
Let's say you have Two Buttons* and **Two Boxes you can have the button_event for the first button trigger the above code and the second button trigger a different code.
Example
WriteText("C:\text2.txt, False, halfnamebox.text)
The best part about creating your own functions and subs are Control I won't get into it, because it will be off topic, but you could check to be sure the textbox has text first before writing the file. This will protect the files integrity.
Hope this helps!
Richard Sites.