• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 360
  • Last Modified:

Reading & Writing from TXT file... Need help in VB.NET

I'm getting a lot of problems while working on VB.NET. Its getting difficult 4 me to read & write the inputs from & to the *.TXT file. I'm explaining the whole scenario, so plz suggest me the full code 4 this program

FORM
-----------

1 - START DATE:  //Inputs the start date
2 - END DATE:      //Inputs the end date
3 - MESSAGE:      //Inputs the message as Reminder Text
4 - "SUBMIT" BUTTON

e.g.
START DATE:    25/03/2006
END DATE:        25/04/2006
MESSAGE:         Check Daily Sales

On pressing the SUBMIT button, the form must close.

For action, the program generates a TXT in a particular directory, let say "DATES_REM.TXT". The form requirments must got written in the TXT file on Line no.s 1,2,3 respectively. e.g.

LINE 1 ------ 25/03/2006
LINE 2 ------ 25/04/2006
LINE 3 ------ Check Daily Sales

Whenever the user logs on to Windows, some file must be accessed which reads the form requirements(all the lines) from TXT file & works according to the following algorithm

IF CURRENT DATE >= 25/03/2006 AND CURRENT DATE <= 25/04/2006 THEN

      MSGBOX "Check Daily Sales"

ELSE
      END DATE = END DATE + 3 (days)
      // The new date after addition must be overwitten in the TXT file on Line 2
END IF
0
eljoseph
Asked:
eljoseph
  • 22
  • 7
1 Solution
 
PockyMasterCommented:
I see issues in your solution. You want to write your datestamp to a text file in the format DD/MM/YYYY.
in case you got dates like this 10/03/2006 or 03/10/2006 you will not be able to read the date format, unless you KNOW it.
It's better to use a date format like DD/MMM/YYYY e.g. 10/jan/2006.
People and software will understand that easier.

OK... your form

add 3 textboxes..

add a button labeled 'Submit'

add the code to the button :
WriteFile() ' let's write the file
Me.Close() 'close ourselves

Import a system.IO to your form, to get the file functionality.

Implement your WriteFile function:

Create a StreamWriter to write your data.
Read your 3 textboxes and write them with your streamwriter to your textfile
don't forget to close your streamwriter

Then create a different app (that's the easiest) or rebuild your first app, since you need the writing part again

Put it in your windows startup e.g.
Create a StreamReader for that.
Use the File.Exists () function in system.io to check if your file exists.
If so, open it with your streamreader
perform readlines to get your data.
Use Convert.ToDate() to convert the string to date types.
Use Now to get the current date and do your compare.


Do your app logic.. and show a messagebox with MessageBox.Show
or call your write function

That's it.
0
 
eljosephAuthor Commented:
PockeyMaster can u plz explain me ur idea with complete code solutions. That would b much helpful then
0
 
PockyMasterCommented:

It's a start I guess,
I create a form containing 2 datepickers:
- dtmStart
- dtmEnd
1 textbox
- txtMessage
1 button
- btnSubmit

good luck


Public Class frmMain

    Private Sub btnSubmit_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSubmit.Click

        If CDateChecker.WriteFile("c:\test.txt", dtmStart.Value, dtmEnd.Value, txtMessage.Text) Then

            Me.Close()
        Else
            MessageBox.Show("Could not write the file")
        End If


    End Sub


    Public Sub New()

        ' This call is required by the Windows Form Designer.
        InitializeComponent()

        ' Add any initialization after the InitializeComponent() call.


        'check our file
        Dim dtmStart As Date
        Dim dtmEnd As Date
        Dim sMessage As String = String.Empty

        If CDateChecker.ReadFile("c:\test.txt", dtmStart, dtmEnd, sMessage) Then
            'do your app logic here
            If Now >= dtmStart AndAlso Now <= dtmEnd Then
                MessageBox.Show(sMessage)

            Else
                dtmEnd.AddDays(3)
                CDateChecker.WriteFile("c:\test.txt", dtmStart, dtmEnd, sMessage)
            End If

            'think about what you want your program to do if the file exists already
            'you might put 'end' here


        Else
            'nothing to do (no file)
        End If

    End Sub
End Class

Imports System.IO

Public Class CDateChecker

    Private Const DATEFORMAT As String = "dd/MMM/yyyy"


    Public Shared Function WriteFile(ByVal FileName As String, ByVal dtmStart As String, ByVal dtmEnd As String, ByVal Message As String) As Boolean
        Return WriteFile(FileName, Convert.ToDateTime(dtmStart), Convert.ToDateTime(dtmEnd), Message)

    End Function

    Public Shared Function WriteFile(ByVal FileName As String, ByVal dtmStart As Date, ByVal dtmEnd As Date, ByVal Message As String) As Boolean

        Dim sw As StreamWriter = Nothing

        Try
            'create the file (always create/overwrite)
            sw = New StreamWriter(FileName, False)

            sw.WriteLine(dtmStart.ToString(DATEFORMAT))
            sw.WriteLine(dtmEnd.ToString(DATEFORMAT))
            sw.WriteLine(Message)

            Return True
        Catch ex As Exception
            MessageBox.Show(ex.Message)
            Return False
        Finally
            If Not sw Is Nothing Then sw.Close()
        End Try


    End Function

    Public Shared Function ReadFile(ByVal FileName As String, ByRef dtmStart As Date, ByRef dtmEnd As Date, ByRef Message As String) As Boolean

        Dim sw As StreamReader = Nothing

        Try
            If Not File.Exists(FileName) Then Return False

            'create the file (always create/overwrite)
            sw = New StreamReader(FileName)

            'normally it's a good habit to check if the string if of type date
            'before you will convert it, but this is for demo purpose
            dtmStart = Convert.ToDateTime(sw.ReadLine())
            dtmEnd = Convert.ToDateTime(sw.ReadLine())
            Message = sw.ReadLine()

            Return True
        Catch ex As Exception
            MessageBox.Show(ex.Message)
            Return False
        Finally
            If Not sw Is Nothing Then sw.Close()
        End Try
    End Function
End Class
0
What does it mean to be "Always On"?

Is your cloud always on? With an Always On cloud you won't have to worry about downtime for maintenance or software application code updates, ensuring that your bottom line isn't affected.

 
eljosephAuthor Commented:
yes PockyMaster exactly its a start

Ok I've made a form, I've added 2 DateTimePickers, 1 TextBox & 1 button. But how can I name DateTimePicker1 as 'dtmStart' & do the same 4 others. What shall we have to do give names to form attributes in Visual Studio .NET 2003.
0
 
eljosephAuthor Commented:
I've just completed a little portion i.e.

Public Class Form1
    Inherits System.Windows.Forms.Form

#Region " Windows Form Designer generated code "

    Public Sub New()
        MyBase.New()

        'This call is required by the Windows Form Designer.
        InitializeComponent()

        'Add any initialization after the InitializeComponent() call

    End Sub

    'Form overrides dispose to clean up the component list.
    Protected Overloads Overrides Sub Dispose(ByVal disposing As Boolean)
        If disposing Then
            If Not (components Is Nothing) Then
                components.Dispose()
            End If
        End If
        MyBase.Dispose(disposing)
    End Sub

    'Required by the Windows Form Designer
    Private components As System.ComponentModel.IContainer

    'NOTE: The following procedure is required by the Windows Form Designer
    'It can be modified using the Windows Form Designer.  
    'Do not modify it using the code editor.
    Friend WithEvents TextBox3 As System.Windows.Forms.TextBox
    Friend WithEvents Label1 As System.Windows.Forms.Label
    Friend WithEvents Label2 As System.Windows.Forms.Label
    Friend WithEvents Label3 As System.Windows.Forms.Label
    Friend WithEvents Button1 As System.Windows.Forms.Button
    Friend WithEvents DateTimePicker1 As System.Windows.Forms.DateTimePicker
    Friend WithEvents DateTimePicker2 As System.Windows.Forms.DateTimePicker
    <System.Diagnostics.DebuggerStepThrough()> Private Sub InitializeComponent()
        Me.TextBox3 = New System.Windows.Forms.TextBox
        Me.Label1 = New System.Windows.Forms.Label
        Me.Label2 = New System.Windows.Forms.Label
        Me.Label3 = New System.Windows.Forms.Label
        Me.Button1 = New System.Windows.Forms.Button
        Me.DateTimePicker1 = New System.Windows.Forms.DateTimePicker
        Me.DateTimePicker2 = New System.Windows.Forms.DateTimePicker
        Me.SuspendLayout()
        '
        'TextBox3
        '
        Me.TextBox3.Location = New System.Drawing.Point(112, 94)
        Me.TextBox3.Name = "TextBox3"
        Me.TextBox3.TabIndex = 2
        Me.TextBox3.Text = "TextBox3"
        '
        'Label1
        '
        Me.Label1.Font = New System.Drawing.Font("Verdana", 8.25!, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
        Me.Label1.Location = New System.Drawing.Point(32, 32)
        Me.Label1.Name = "Label1"
        Me.Label1.Size = New System.Drawing.Size(72, 23)
        Me.Label1.TabIndex = 3
        Me.Label1.Text = "Start Date"
        '
        'Label2
        '
        Me.Label2.Font = New System.Drawing.Font("Verdana", 8.25!, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
        Me.Label2.Location = New System.Drawing.Point(39, 64)
        Me.Label2.Name = "Label2"
        Me.Label2.Size = New System.Drawing.Size(64, 23)
        Me.Label2.TabIndex = 4
        Me.Label2.Text = "End Date"
        '
        'Label3
        '
        Me.Label3.Font = New System.Drawing.Font("Microsoft Sans Serif", 8.25!, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
        Me.Label3.Location = New System.Drawing.Point(47, 96)
        Me.Label3.Name = "Label3"
        Me.Label3.Size = New System.Drawing.Size(56, 23)
        Me.Label3.TabIndex = 5
        Me.Label3.Text = "Message"
        '
        'Button1
        '
        Me.Button1.Location = New System.Drawing.Point(136, 136)
        Me.Button1.Name = "Button1"
        Me.Button1.TabIndex = 6
        Me.Button1.Text = "Submit"
        '
        'DateTimePicker1
        '
        Me.DateTimePicker1.Location = New System.Drawing.Point(112, 29)
        Me.DateTimePicker1.Name = "DateTimePicker1"
        Me.DateTimePicker1.TabIndex = 7
        '
        'DateTimePicker2
        '
        Me.DateTimePicker2.Location = New System.Drawing.Point(111, 62)
        Me.DateTimePicker2.Name = "DateTimePicker2"
        Me.DateTimePicker2.TabIndex = 8
        '
        'Form1
        '
        Me.AutoScaleBaseSize = New System.Drawing.Size(5, 13)
        Me.ClientSize = New System.Drawing.Size(336, 182)
        Me.Controls.Add(Me.DateTimePicker2)
        Me.Controls.Add(Me.DateTimePicker1)
        Me.Controls.Add(Me.Button1)
        Me.Controls.Add(Me.Label3)
        Me.Controls.Add(Me.Label2)
        Me.Controls.Add(Me.Label1)
        Me.Controls.Add(Me.TextBox3)
        Me.Name = "Form1"
        Me.Text = "Form1"
        Me.ResumeLayout(False)

    End Sub

#End Region

    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load

    End Sub

    Private Sub Label1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Label1.Click

    End Sub

    Private Sub Label3_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Label3.Click

    End Sub

    Private Sub btnSubmit_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSubmit.Click
        If CDateChecker.WriteFile("c:\Dates.txt", dtmStart.Value, dtmEnd.Value, txtMessage.Value) Then
            Me.Close()
        Else
            MessageBox.Show("Could not write the file")
        End If
    End Sub
End Class

It gives me the following list of erros why? I think there's some problem with Initialization of variables

Handles clause requires a WithEvents variable.
Name 'CDateChecker' is not declared.
Name 'dtmStart' is not declared.
Name 'dtmEnd' is not declared.
Name 'txtMessage' is not declared.
0
 
eljosephAuthor Commented:
wht 2 do 2 remove these errors?
0
 
eljosephAuthor Commented:
ok PockyMaster I've done everthing as u said...... I've debug the application & it generates just 1 error..... Its unable to understood. Plz tell me how to resolve it

C:\.......\Form1.vb(151): 'Value' is not a member of 'System.Windows.Forms.TextBox'.

On Double Click it points to "txtMessage.Value" in the first function u defined. Tell me its solution plzzzzzzzz
0
 
eljosephAuthor Commented:
ooppss soory i got my mistake
0
 
eljosephAuthor Commented:
ok its done PocketMaster...... but I have noticed 1 mistake....... I changed my system date to 26/Apr/2006. Its fine that the MsgBox didn't appear & the program might have successfully added 3 days to the End Date.

But when I checked the "test.txt" file, the End Date remains the same. Its should b changed to 28/Apr/2006. But it isn't. Why is it so?

Moreover u told me the whole code within a single file. Is it possible if I could separate it in 2 files, so that the form doesn't always appear. For the purpose what Project Application shall I use, either Windows Script or Console Application?
0
 
PockyMasterCommented:
Uhm, sorry I couldnt answer your previous questions, I was out.
When I look at the form you pasted, it doesnt have the part I copied in my example in my frmMain.
That's were the 3 days add stuff happens.

You could create a simple console application, put that stuff in your sub main and copy the class file into that project as well.
Put the file in your startup and you're done.

0
 
eljosephAuthor Commented:
Here I separated the following code 4 ConsoleApplication bit generates an error "MessageBox" not declared

Imports System.IO

Module Module1

    Sub Main()
        Dim dtmStart As Date
        Dim dtmEnd As Date
        Dim sMessage As String = String.Empty

        If CDateChecker.ReadFile("c:\Dates.txt", dtmStart, dtmEnd, sMessage) Then
            If Now >= dtmStart AndAlso Now <= dtmEnd Then
                MessageBox.Show(sMessage)
            Else
                dtmEnd = dtmEnd.AddDays(3)
                CDateChecker.WriteFile("c:\Dates.txt", dtmStart, dtmEnd, sMessage)
            End If
        End If
    End Sub

End Module

Public Class CDateChecker
    Private Const DATEFORMAT = "dd/MMM/yyyy"

    Public Shared Function WriteFile(ByVal FileName As String, ByVal dtmStart As String, ByVal dtmEnd As String, ByVal Message As String) As Boolean
        Return WriteFile(FileName, Convert.ToDateTime(dtmStart), Convert.ToDateTime(dtmEnd), Message)
    End Function

    Public Shared Function WriteFile(ByVal FileName As String, ByVal dtmStart As Date, ByVal dtmEnd As Date, ByVal Message As String) As Boolean
        Dim sw As StreamWriter = Nothing

        Try
            sw = New StreamWriter(FileName, False)
            sw.WriteLine(dtmStart.ToString(DATEFORMAT))
            sw.WriteLine(dtmEnd.ToString(DATEFORMAT))
            sw.WriteLine(Message)
            Return True
        Catch ex As Exception
            MessageBox.Show("ex.Message")
            Return False
        Finally
            If Not sw Is Nothing Then sw.Close()
        End Try
    End Function

    Public Shared Function ReadFile(ByVal FileName As String, ByVal dtmStart As Date, ByVal dtmEnd As Date, ByVal Message As String) As Boolean
        Dim sw As StreamReader = Nothing

        If Not File.Exists(FileName) Then Return False

        Try
            sw = New StreamReader(FileName)
            dtmStart = Convert.ToDateTime(sw.ReadLine())
            dtmEnd = Convert.ToDateTime(sw.ReadLine())
            Message = sw.ReadLine()
            Return True
        Catch ex As Exception
            MessageBox.Show(ex.Message)
        Finally
            If sw Is Nothing Then sw.Close()
        End Try
    End Function
End Class
0
 
eljosephAuthor Commented:
How to remove 'Name "MessageBox" not declared' error?
0
 
eljosephAuthor Commented:
I tried the READ code in a separate WindowsApplication as well but there I get the following 2 errors

1 - "This process cannot access the file 'c:\Dates.txt' because it is being used by another process"

2 - "An unhandled exception error has occurred in your application"

How to resolve them?
0
 
PockyMasterCommented:
In console you might use System.Windows.Forms.MessageBox
If you write to it, but don't close it, you could get .1
or maybe you opened it exclusively from another application
0
 
eljosephAuthor Commented:
I used this IMPORT but gives an error

"Namespace or type 'MessageBox' for the Imports 'System.Windows.Forms.MessageBox' cannot be found."

wht 2 do then?
0
 
eljosephAuthor Commented:
ok I simply tried PROJECT ---> ADD REFERENCE ---> Added System.Windows.Forms.dll. I worked somehow by importing System.Windows.Forms but returns a new error ,i.e

"This process cannot access the file 'c:\Dates.txt' because it is being used by another process"
0
 
PockyMasterCommented:
No, don't import System.Windows.Forms.MessageBox,
but import System.Windows.Forms
that will allow you to use the MessageBox.

0
 
eljosephAuthor Commented:
ok ur code is working fine now in separate files

but there's a little problem. 3 dayz r not added if I change the system date(greater than the END DATE in TXT file). WHY?

Moreover is there any way if we make the Console DOS window hidden on every system login. B'coz after login, the Console Window appears, logic is checked & then the MsgBox appears. Is it possible if we can make the Console Window hidden?

Plz reply me back
0
 
eljosephAuthor Commented:
I've 2 leave now as it off time but I'll check 4 u replies at home
0
 
PockyMasterCommented:
Yeah, there is a way:

go to solution properties:
Change your project type to a windows application
Disable the application framework checkbox

Select your sub Main to be your startup.
Just don't create any form, and you will have no console, and no forms.

0
 
eljosephAuthor Commented:
Where shall I find SOLUTION PROPERTIES in Visual Studio.NET 2003?
0
 
eljosephAuthor Commented:
n u didn't reply 4 no. of days to be added.....

According to you program 3 dayz r not added on changing the system's date. Why?
0
 
eljosephAuthor Commented:
ok I simply did the following

PROJECT -> CONSOLEAPPLICATION1 PROPERTIES -> GENERAL

Here I can change the project type 2 Windows Application & set Sub Main as Start Up.

But I cannot see the "application framework" checkbox there. So how could I disable it?
0
 
eljosephAuthor Commented:
I couldn't find the "application framework" checkbox anywhere but anyhow changing the project type to Windows Application & setting Sub Main as Start Up Module helped me get what I wanted

Thanx so far

But now just have a quick look at ur code & lemme know why 3 dayz r not added on extending the END DATE

plzzzz plzzz reply
0
 
eljosephAuthor Commented:
any clues why xtra dayz r not being added?
0
 
eljosephAuthor Commented:
Hey Guyz I could not get the solution so plz help me out
0
 
eljosephAuthor Commented:
Why its not adding 3 dayz PockyMaster?
0
 
PockyMasterCommented:
Because I was sleeping when I wrote the example I guess.

dtmEnd =  dtmEnd.AddDays(3)

dtmEnd will return a date 3 days after dtmEnd, it would be nice if dtmEnd knew about that as well :D
0
 
eljosephAuthor Commented:
Thank u so much PockyMaster...... u did a great job

Now I truly belive this forum is the best of all..

Actually ur previous code was correct. The mistake was from my side. I was writing the Added Date to some other TXT file. That's why I couldn't view the correct output.

Anywayz thanx very much. I'm really obliged 2 u
0

Featured Post

Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

  • 22
  • 7
Tackle projects and never again get stuck behind a technical roadblock.
Join Now