2011-09-11 33 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); 

,并用它做。该框架将处理文件访问问题。