2011-09-11 61 views
0

我正在創建一個Windows服務,以保存CSV文件中的當前用戶名和登錄時間。但是當我安裝服務時,文件剛剛創建,沒有細節被寫入,並且該文件被設置爲只讀模式。我的代碼中有什麼問題?使用Windows服務創建,更新,使用C#或VB.net刪除CSV文件

我的代碼:

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 
+1

儘量不要忽略異常,這可能會回答你的問題。 –

+0

感謝您的回覆。那麼如何編寫代碼 – Karthik

回答

1

有很多方法來解決你在做什麼。

對於1,您不需要讀入整個文件以追加到文件末尾。例如

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

但是,您將遇到併發訪問該文件的問題。你會更好使用日誌框架,例如log4net的或Microsoft日誌程序塊,然後就

Logger.Info(yourstring); 

,並用它做。該框架將處理文件訪問問題。