0

I am creating a windows service to save current username and logon time in a CSV file. But when I install the service, the file is just created, not details are written to it, and that file is set to read-only mode. what is the problem in my code?

My code:

   Imports System.IO
   Imports System.Text
   Imports System.DirectoryServices
   Imports System.DirectoryServices.AccountManagement
   Imports System.Diagnostics
   Public Class LoginService1

      Protected Overrides Sub OnStart(ByVal args() As String)
        Dim win As System.Security.Principal.WindowsIdentity
        win = System.Security.Principal.WindowsIdentity.GetCurrent()
        Dim Logon_UserName = win.Name.Substring(win.Name.IndexOf("\") + 1)
        Dim pc As New PrincipalContext(ContextType.Machine, My.Computer.Name)
        Dim uc As UserPrincipal = UserPrincipal.FindByIdentity(pc, Logon_UserName)
        Dim str As String = ""
        Try
           Dim sr As New StreamReader("c:\logondetails.csv")
           str = sr.ReadToEnd()
           sr.Close()
           sr.Dispose()
        Catch ex As Exception
        End Try
        Try
           Dim sw As New StreamWriter("c:\logondetails.csv")
           Str += Logon_UserName & "," & uc.LastLogon.Value.ToString
           sw.WriteLine(str)
           sw.Close()
           sw.Dispose()
        Catch ex As Exception
        End Try
   End Sub

   Protected Overrides Sub OnStop()
      ' Add code here to perform any tear-down necessary to stop your service.'
   End Sub

  End Class
2
  • 1
    Try not ignoring the exception, this will probably answer your question. Sep 11, 2011 at 19:56
  • thanks for reply. then how to write coding
    – Karthik
    Sep 11, 2011 at 19:58

1 Answer 1

1

There are many ways to fix what you are doing.

For 1, you dont need to read in the entire file to append to the end of it. For example

using(var stream = File.AppendText(fileName))
            {
            stream.Write(string);
            stream.Close();
            }

But you are going to have issues with concurrent access to the file. You'd be better off using a logging framework, such as log4net or microsoft logging block, and then just

Logger.Info(yourstring);

and be done with it. The framework will handle the file access issues.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.