Windows Service在Windows服务系统中安装后不写入文本文件

时间:2014-04-11 04:52:40

标签: c# windows windows-services windows-server-2008 text-files

我已经制作了一个包含套接字连接代码的Windows服务。根据安装此Windows服务后的代码,启动后,它应该将一些消息写入文本文件,但我无法看到任何消息在我的本地PC中包含Windows 7,我的这个服务能够写入文本文件。 这是我的代码..

            try
            {
                using (StreamWriter writer = new StreamWriter(textfileSaveLocation, true))
                {
                    writer.WriteLine("Before Connection !");
                }

                client.Connect(new IPEndPoint(IPAddress.Parse(ip), intport));

                Thread.Sleep(5000);

                using (StreamWriter writer = new StreamWriter(textfileSaveLocation, true))
                {
                    writer.WriteLine("Connected To Machine !");
                }

            }
           catch (Exception ex)
            {
                // Log the error here.
                client.Close();

                using (StreamWriter writer = new StreamWriter(textfileSaveLocation, true))
                {
                    writer.WriteLine("Connection Error !");
                }

                continue;
            }

所以我怀疑为什么我的服务无法在本地系统中写入服务器文本文件。服务器PC中还有其他文本文件从其他人那里获取来自其他Windows服务的消息为什么我的情况会发生这种情况? 请帮我。 提前谢谢。

2 个答案:

答案 0 :(得分:4)

检查以下内容:

  1. 运行Windows服务的帐户对文件夹路径具有写入权限。
  2. 文件夹路径正确。
  3. 您可能正在本地服务器上以管理员身份运行该服务,因此它具有所有权限。
  4. 同样在您的Exception块中,确保记录ex.ToString()。它提供了很多信息。
  5. 您的client.Close()也可以引发异常。照顾那种情况。
  6. 如果存在文件访问问题,请先放置一个uber try / catch块,然后尝试将文本文件写在公共文件夹上,然后您知道Everyone有权访问。

答案 1 :(得分:0)

serviceProcessInstaller 中,您应将帐户属性设置为 LocalSystem 。这将导致服务安装并在本地服务帐户上运行。