Visual Basic Deleting Unmodified Files - visual-studio-2010

The following code will extract files from one Folder and Place them another as you can see. But I am trying to delete the files that have not been modified in the past 3 months, and it does not delete any files at all.
Code:
Imports System.IO
Public Class frmExtractionator
Dim txtFiles1 As Control
Private Sub btnStart_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnStart.Click
Dim sourceDirectory As String = "E:\CopierFolderforTestDriveCapstone"
Dim archiveDirectory As String = "E:\FilesExtracted"
Try
Dim txtFiles = Directory.EnumerateFiles(sourceDirectory)
If (Not System.IO.Directory.Exists(archiveDirectory)) Then
System.IO.Directory.CreateDirectory(archiveDirectory)
End If
For Each currentFileLoc As String In txtFiles
Dim fileName = currentFileLoc.Substring(sourceDirectory.Length + 1)
File.Move(currentFileLoc, Path.Combine(archiveDirectory, fileName))
Try
Dim di As DirectoryInfo = New DirectoryInfo(sourceDirectory)
Dim fi As FileInfo() = di.GetFiles()
For Each currentFile As FileInfo In fi
File.Move(currentFile.FullName, Path.Combine(archiveDirectory, currentFile.Name))
Dim dt As DateTime = currentFile.LastWriteTime
' Add 3 months to the last write and check if it is less than today '
If dt.AddMonths(3) < DateTime.Today Then
File.Delete(currentFile.FullName)
End If
Next
Catch eT As Exception
Console.WriteLine(eT.Message)
End Try
Next
Catch eT As Exception
Console.WriteLine(eT.Message)
End Try
End Sub
End Class

Related

Reading a specified line of an external file on Visual Basic [duplicate]

I am creating a program that is supposed to write text into a text file, and should be able to read specific lines from a text file in VB (so if i needed to read a specific name I could select line 5 and it would display in the textbox). I am able to read the text from the text file but I do not know how to control a specific line.
Here is my code:
Public Class Form1
Private Sub btnSubmit_Click(sender As System.Object, e As System.EventArgs) Handles btnSubmit.Click
Dim writer As New System.IO.StreamWriter("/text.txt", True)
writer.WriteLine(txtFirstName.Text)
writer.WriteLine(txtLastName.Text)
writer.WriteLine("-------------------------------------")
writer.Close()
End Sub
Private Sub btnRead_Click(sender As System.Object, e As System.EventArgs) Handles btnRead.Click
Dim reader As New System.IO.StreamReader("/text.txt")
Dim FirstName, LastName As String
FirstName = reader.ReadLine()
LastName = reader.ReadLine()
reader.Close()
txtFirstName.Text = FirstName
txtLastName.Text = LastName
End Sub
Private Sub btnClear_Click(sender As System.Object, e As System.EventArgs) Handles btnClear.Click
txtFirstName.Clear()
txtLastName.Clear()
End Sub
End Class
Any help would be appreciated. Thanks!
You will have to read all lines up to the one you're interested in. For example:
Function ReadLineWithNumberFrom(filePath As String, ByVal lineNumber As Integer) As String
Using file As New StreamReader(filePath)
' Skip all preceding lines: '
For i As Integer = 1 To lineNumber - 1
If file.ReadLine() Is Nothing Then
Throw New ArgumentOutOfRangeException("lineNumber")
End If
Next
' Attempt to read the line you're interested in: '
Dim line As String = file.ReadLine()
If line Is Nothing Then
Throw New ArgumentOutOfRangeException("lineNumber")
End If
' Succeded!
Return line
End Using
End Function
This is because lines of text are variable-length records, and there is no way to guess the exact file offset where a specific line begins — not without an index.
If you frequently need to load a specific line, you have some more options:
Load the complete text file into memory, e.g. by using File.ReadAllLines("Foobar.txt"). This returns a String() array which you can access by line number directly.
Create a line number index manually. That is, process a text file line by line, and fill a Dictionary(Of Integer, Integer) as you go. The keys are line numbers, and the values are file offsets. This allows you to .Seek right to the beginning of a specific line without having to keep the whole file in memory.
Try this:
Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
Dim reader As New System.IO.StreamReader("C:\text.txt")
Dim allLines As List(Of String) = New List(Of String)
Do While Not reader.EndOfStream
allLines.Add(reader.ReadLine())
Loop
reader.Close()
txtFirstName.Text = ReadLine(5, allLines)
txtLastName.Text = ReadLine(6, allLines)
End Sub
Public Function ReadLine(lineNumber As Integer, lines As List(Of String)) As String
Return lines(lineNumber - 1)
End Function
If you had a file with this:
Line 1
Line 2
Line 3
Line 4
My Name
My LastName
your name textbox will have 'My Name' and your LastName textbox will have 'My LastName'.
This is very simple, try this:
Dim strLineText As String
Dim intLineNumber As Integer
LineNumber=3
myLine = File.ReadAllLines("D:\text.txt").ElementAt(LineNumber).ToString
Yet another option
Private Function readNthLine(fileAndPath As String, lineNumber As Integer) As String
Dim nthLine As String = Nothing
Dim n As Integer
Try
Using sr As StreamReader = New StreamReader(fileAndPath)
n = 0
Do While (sr.Peek() >= 0) And (n < lineNumber)
sr.ReadLine()
n += 1
Loop
If sr.Peek() >= 0 Then
nthLine = sr.ReadLine()
End If
End Using
Catch ex As Exception
Throw
End Try
Return nthLine
End Function
i tried this and it works fine. using VB Express
content inside test.txt:
line1
line2
1
John
then in the form i add
textbox1
textbox2
label1
label2
and a button.
code inside the button:
Private Sub Button2_Click_1(sender As Object, e As EventArgs) Handles Button2.Click
Dim myLine As String
Dim lineNumber0 As Integer
lineNumber0 = 0
Dim lineNumber1 As Integer
lineNumber1 = 1
Dim lineNumber2 As Integer
lineNumber2 = 2
Dim lineNumber3 As Integer
lineNumber3 = 3
TextBox1.Text=File.ReadAllLines("D:\test.txt").ElementAt(lineNumber0).ToString
TextBox2.Text=File.ReadAllLines("D:\test.txt").ElementAt(lineNumber1).ToString
Label1.Text = File.ReadAllLines("D:\test.txt").ElementAt(lineNumber2).ToString
Label2.Text = File.ReadAllLines("D:\test.txt").ElementAt(lineNumber3).ToString
End Sub
Here's a simple but effective solution:
Dim Reader As String = System.IO.File.ReadAllLines("C:\File.txt")(1)
MsgBox("Line 1: " + Reader)
The MsgBox should show the first line of C:\File.txt.

edit through visual studio an msword file

i am trying a program that can edit an existing ms word document through an instant editing at a visual studio 2010 program but im having trouble. my codes:
Imports Microsoft.Office.Interop
Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim wd1 As Word.Application
Dim wd1Doc As Word.Document
wd1 = New Word.Application
wd1.Visible = True
wd1Doc = wd1.Documents.Add("C:\Users\DELL\Desktop\activity6\profile.dotx")
With wd1Doc
.FormFields("w_name").Range = TextBox1.Text
.FormFields("w_age").Range = TextBox2.Text
End With
wd1 = Nothing
wd1Doc = Nothing
End Sub
End Class
the errors says: "property range is read only"
Your code is almost correct. If you want to the the text of a Range object, you need to use its .Text property:
With wd1Doc
.FormFields("w_name").Range.Text = TextBox1.Text
.FormFields("w_age").Range.Text = TextBox2.Text
End With

How to write data to a file in Visual Studios?

I'm writing a program that reads an input file that contains a line:
Scott Atchison,200,74
The file contains around 30 different lines of data. I know how to read in the file. After the file is read in it is split and then a calculation needs to be done (I know how to do that).
However, the problem that I have is the output file, I can get only the last line of the input file to the output file. This is what I have right now:
Public Class BMI
Dim data As String
Dim strName As String
Dim intWeight As Integer
Dim intHeight As Integer
Dim decBMI As Decimal
Private Sub btnInputFile_Click(sender As System.Object, e As System.EventArgs) Handles btnOpenFile.Click
'User chooses a file
OpenFile.ShowDialog()
'Choose a file name into a label
lblFileInput.Text = OpenFile.FileName
Dim inputFile As New IO.StreamReader(lblFileInput.Text)
Do While (inputFile.Peek() > -1)
data = inputFile.ReadLine
Dim fields() As String = data.Split(",")
strName = fields(0)
intWeight = fields(1)
intHeight = fields(2)
txtData.Text = txtData.Text & data & vbNewLine
Loop
FileClose()
End Sub
Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles btnSaveFile.Click
SaveFile.ShowDialog()
lblFileOutput.Text = SaveFile.FileName
Dim output As IO.StreamWriter
output = New IO.StreamWriter(lblFileOutput.Text)
output.WriteLine(data)
End Sub
Private Sub Button1_Click_1(sender As System.Object, e As System.EventArgs) Handles Button1.Click
decBMI = (intWeight * 703 / (intHeight ^ 2))
data = strName & ", " & decBMI
End Sub
End Class
Wouldn't it write a line until all 30 lines are read, or Am I missing something, like a while loop? Any help would be appreciated.
It would be nice if you gave us a nice, executable, snippet of code, including declarations of all your variables. For instance, where is "data" defined. What is the relationship between both chunks of code? Are they in the same procedure?
The first thing I notice is that you are splitting each line, "data", into fields, saving them into variables, which you just ignore. You then append "data" to a text box.
Assuming that "data" is shared between the two chunks of code, then reason for your problem is that the value being written to the streamwriter is the last value of "data", which happens to be the last line that was read into it.

Visual Basic - Copying the only Recently Modified Files to another Folder

the following code I have hear will extract all the files inside of a certain folder, and then copy all of them and place them into another folder. My question today is how do I modify this code so that only files extracted from the original folder have been recently modified. Even if you could show me how to extract only the files that have been modified from today would be great. Thanks to all of you who help!
Imports System.IO
Public Class frmExtractionator
Dim txtFiles1 As Control
Private Sub btnStart_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnStart.Click
Dim sourceDirectory As String = "E:\CopierFolderforTestDriveCapstone"
Dim archiveDirectory As String = "E:\FilesExtracted"
Try
'DeleteUnmodifiedFiles(sourceDirectory, -14)
Dim txtFiles = Directory.EnumerateFiles(sourceDirectory)
If (Not System.IO.Directory.Exists(archiveDirectory)) Then
System.IO.Directory.CreateDirectory(archiveDirectory)
End If
For Each currentFileLoc As String In txtFiles
Dim fileName = currentFileLoc.Substring(sourceDirectory.Length + 1)
File.Move(currentFileLoc, Path.Combine(archiveDirectory, fileName))
Next
Catch eT As Exception
Console.WriteLine(eT.Message)
End Try
End Sub
You can use the Directory.GetLastWriteTime Method to determine when the file was last written to.
From Link:
Returns the date and time the specified file or directory was last written to.
Dim checkDate As Date = Date.Parse("01/1/2013")
For Each currentFileLoc As String In txtFiles
Dim fileName = currentFileLoc.Substring(sourceDirectory.Length + 1)
If Directory.GetLastWriteTime(Path.Combine(sourceDirectory, fileName)) > checkDate Then
File.Move(currentFileLoc, Path.Combine(archiveDirectory, fileName))
End If
Next

problem with .net windows service

have written a windows service. while the code worked for a simple form app, its not working in a windows service. here;s the code
Imports System.Text.RegularExpressions
Imports System.Net.Sockets
Imports System.Net
Imports System.IO
Public Class Service1
Public Shared Function CheckProxy(ByVal Proxy As String) As Boolean
Dim myWebRequest As HttpWebRequest = CType(WebRequest.Create("http://google.com"), HttpWebRequest)
myWebRequest.Proxy = New WebProxy(Proxy, False)
myWebRequest.Timeout = 10000
Try
Dim myWebResponse As HttpWebResponse = CType(myWebRequest.GetResponse(), HttpWebResponse)
Dim loResponseStream As StreamReader = New StreamReader(myWebResponse.GetResponseStream())
Return True
Catch ex As WebException
If (ex.Status = WebExceptionStatus.ConnectFailure) Then
End If
Return False
End Try
End Function
Protected Overrides Sub OnStart(ByVal args() As String)
System.IO.File.AppendAllText("C:\AuthorLog.txt",
"AuthorLogService has been started at " & Now.ToString())
MsgBox("1")
Timer1.Enabled = True
End Sub
Protected Overrides Sub OnStop()
' Add code here to perform any tear-down necessary to stop your service.
Timer1.Enabled = False
End Sub
Private Sub Timer1_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer1.Tick
MsgBox("2")
' Check if the the Event Log Exists
If Not Diagnostics.EventLog.SourceExists("Evoain Proxy Bot") Then
Diagnostics.EventLog.CreateEventSource("MyService", "Myservice Log") ' Create Log
End If
' Write to the Log
Diagnostics.EventLog.WriteEntry("MyService Log", "This is log on " & _
CStr(TimeOfDay), EventLogEntryType.Information)
Dim ProxyURLList As New Chilkat.CkString
Dim ProxyListPath As New Chilkat.CkString
Dim WorkingProxiesFileData As New Chilkat.CkString
Dim ProxyArray(10000000) As String
Dim event1 As New Chilkat.CkString
event1.setString("started")
event1.saveToFile("B:\serv.txt", "utf-8")
Dim ns As Integer = 0
'Read Configuration File
Dim sFileName As String
Dim srFileReader As System.IO.StreamReader
Dim sInputLine As String
sFileName = "config.ini"
srFileReader = System.IO.File.OpenText(sFileName)
sInputLine = srFileReader.ReadLine()
Dim temp As New Chilkat.CkString
Do Until sInputLine Is Nothing
temp.setString(sInputLine)
If temp.containsSubstring("proxyurllist=") = True Then
'Read Proxy-URL-List
ProxyURLList.setString(sInputLine)
If ProxyURLList.containsSubstring("proxyurllist=") = True Then
ProxyURLList.replaceFirstOccurance("proxyurllist=", "")
End If
ElseIf temp.containsSubstring("finalproxylistpath=") = True Then
'Read Proxy-List-Path
ProxyListPath.setString(sInputLine)
If ProxyListPath.containsSubstring("finalproxylistpath=") = True Then
ProxyListPath.replaceFirstOccurance("finalproxylistpath=", "")
End If
End If
sInputLine = srFileReader.ReadLine()
Loop
'*********Scrape URLs From Proxy-URL-List*********************
Dim ProxyURLFileData As New Chilkat.CkString
ProxyURLFileData.loadFile(ProxyURLList.getString, "utf-8")
Dim MultiLineString As String = ProxyURLFileData.getString
Dim ProxyURLArray() As String = MultiLineString.Split(Environment.NewLine.ToCharArray, System.StringSplitOptions.RemoveEmptyEntries)
Dim i As Integer
For i = 0 To ProxyURLArray.Count - 1
'********Scrape Proxies From Proxy URLs***********************
Dim http As New Chilkat.Http()
Dim success As Boolean
' Any string unlocks the component for the 1st 30-days.
success = http.UnlockComponent("Anything for 30-day trial")
If (success <> True) Then
Exit Sub
End If
' Send the HTTP GET and return the content in a string.
Dim html As String
html = http.QuickGetStr(ProxyURLArray(i))
Dim links As MatchCollection
links = Regex.Matches(html, "[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}:[0-9]{1,5}")
For Each match As Match In links
Dim matchUrl As String = match.Groups(0).Value
ProxyArray(ns) = matchUrl
ns = ns + 1
Next
Next
'*************CHECK URLs*****************
Dim cnt As Integer = 0
For cnt = 0 To 1
Dim ProxyStatus As Boolean = CheckProxy("http://" + ProxyArray(cnt) + "/")
If ProxyStatus = True Then
WorkingProxiesFileData.append(Environment.NewLine)
WorkingProxiesFileData.append(ProxyArray(cnt))
End If
Next
WorkingProxiesFileData.saveToFile(ProxyListPath.getString, "utf-8")
End Sub
End Class
what are the basic thing i cannot do in a windows service? oh, and i am using the chilkat library too..
why can't i use all of my code in OnStart? i did so and the services stops just as it starts.
can i use something else except a timer and put an endless loop?
Running as a windows service typically won't let you see any popup boxes, etc since there's no UI (Unless you check the box to allow interaction with the desktop).
Try adding a Timer1.Start in your OnStart method. Then in your Timer1_Tick method, first thing stop the timer, then at the end start it back up, this way your Tick method won't fire while you're already doing work.
I realize I'm (very) late to this party, but what kind of timer are you using? A System.Windows.Forms.Timer is designed for use in a single threaded Windows Form and will not work in a Windows Service app. Try a System.Timers.Timer instead.

Resources