使用Windows服务使用C#或VB.net创建、更新、删除CSV文件

使用Windows服务使用C#或VB.net创建、更新、删除CSV文件,c#,vb.net,C#,Vb.net,我正在创建一个windows服务,将当前用户名和登录时间保存在CSV文件中。但当我安装该服务时,文件只是创建的,没有写入详细信息,并且该文件被设置为只读模式。我的代码中有什么问题 我的代码: Imports System.IO 导入系统文本 导入System.DirectoryServices 导入System.DirectoryServices.AccountManagement 导入系统。诊断 公共类登录服务1 受保护的重写子启动(ByVal args()作为字符串) Dim win作为Sy

我正在创建一个windows服务,将当前用户名和登录时间保存在CSV文件中。但当我安装该服务时,文件只是创建的,没有写入详细信息,并且该文件被设置为只读模式。我的代码中有什么问题

我的代码:

Imports System.IO
导入系统文本
导入System.DirectoryServices
导入System.DirectoryServices.AccountManagement
导入系统。诊断
公共类登录服务1
受保护的重写子启动(ByVal args()作为字符串)
Dim win作为System.Security.Principal.WindowsIdentity
win=System.Security.Principal.WindowsIdentity.GetCurrent()
Dim Logon\u UserName=win.Name.Substring(win.Name.IndexOf(“\”)+1)
Dim pc作为新的PrincipalContext(ContextType.Machine、My.Computer.Name)
Dim uc As UserPrincipal=UserPrincipal.FindByIdentity(pc,登录\用户名)
Dim str As String=“”
尝试
Dim sr作为新的StreamReader(“c:\logondetails.csv”)
str=sr.ReadToEnd()
高级关闭()
高级行政主任()
特例
结束尝试
尝试
Dim sw作为新的StreamWriter(“c:\logondetails.csv”)
Str+=Logon\u用户名&“,”&uc.LastLogon.Value.ToString
西南写入线(str)
sw.Close()
sw.Dispose()
特例
结束尝试
端接头
受保护的覆盖子桌面()
'在此处添加代码以执行停止服务所需的任何拆卸操作。'
端接头
末级

有很多方法可以解决您正在做的事情

对于1,您不需要读入整个文件以附加到它的末尾。比如说

using(var stream = File.AppendText(fileName))
            {
            stream.Write(string);
            stream.Close();
            }
但是您将遇到并发访问文件的问题。您最好使用日志框架,如log4net或microsoft日志块,然后

Logger.Info(yourstring);

就这样吧。框架将处理文件访问问题。

请不要忽略此异常,这可能会回答您的问题。谢谢您的回复。那么如何编写代码呢