Windows服务写入文件 - UnauthorizedAccessException

时间:2017-03-28 19:13:03

标签: c# windows-services file-permissions

从Windows服务写入FileSystem

从控制台应用程序我可以使用写入文件     System.IO.File.WriteAllText(@"C:\_dev\some_path\Log.txt", "new file additions");

但是在我的新Windows服务中使用相同的代码我无法通过以下原因完成相同的操作:

`Service cannot be started. System.Exception: unable to save file! - 
filePath=C:\_dev\some_path\Log.txt 
type=System.UnauthorizedAccessException , 
message=Access to the path 'C:\WINDOWS\system32\filePath' is denied.
innerException=, 
stackTrace=   at System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath)
   at System.IO.FileStream.Init(String path, FileMode mode, FileAccess access, Int32 rights, Boolean useRights, FileShare share, Int32 bufferSize, FileOptions options, SECURITY_ATTRIBUTES secAttrs, String msgPath, Boolean bFromProxy, Boolean useLongPath, Boolean checkHost)
   at System.IO.FileStream..ctor(String path, FileMode mode, FileAccess access, FileShare share, Int32 bufferSize, FileOptions options, String msgPath, Boolean bFromProxy, Boolean useLongPath, Boolean checkHost)
   at System.IO.StreamWriter.CreateFile(String path, Boolean append, Boolean checkHost)
   at System.IO.StreamWriter..ctor(String path, Boolean append, Encoding encoding, Int32 bufferSize, Boolean checkHost)
   at Sys...`

为什么要使用文件路径C:\WINDOWS\system32\filePath?我在WriteAllText()中指定的文件路径是C:\_dev\some_path\Log.txt

我确信这与Idendity有关,但我是使用Windows服务的新手,我确信我只是忽略了一些简单的事情。

有访问权限的当前用户: 1.经过身份验证的用户 2.系统 3.管理员(COMPUTER \ Administrators) 4.用户(COMPUTER \ Users)

我也试过并添加了这些帐户,但仍然遇到同样的错误 5.本地服务 6.服务 7. IUSR

我的Windows服务如何写入文件,为什么WriteAllText()会尝试使用C:\WINDOWS\system32

1 个答案:

答案 0 :(得分:2)

仍然没有写入磁盘,而是开始服务:

  1. 单击“登录”选项卡
  2. 选择“本地系统帐户” 一个。选中“允许服务与桌面交互”