简体   繁体   English

即使以管理员身份运行,我的程序也无法写入HOSTS文件

[英]My Program cannot write HOSTS file even when run as Admin

I have a strange problem. 我有一个奇怪的问题。 I am writing an application in C# (.Net 4 client profile) which will change entries in the HOSTS file. 我正在用C#(。Net 4客户端配置文件)编写一个应用程序,它将更改HOSTS文件中的条目。 I added "full access" to my user account for the HOSTS file and I can edit the file without any problems in normal text editors. 我向HOSTS文件的用户帐户添加了“完全访问权限”,并且可以在普通文本编辑器中毫无问题地编辑文件。

The application works find when run in the Visual Studio 2010 Debugger (when "Enable the Visual Studio hosting process" is selected). 当在Visual Studio 2010调试器中运行时(当选择“启用Visual Studio托管过程”时),该应用程序将工作。

When I run the application outside of Visual Studio, even when "run as Admin" (!!!) I can a UnauthorizedAccessException when trying to write the HOSTS file. 当我在Visual Studio外部运行应用程序时,即使“以管理员身份运行”(!!!),也可以在尝试编写HOSTS文件时出现UnauthorizedAccessException。 Why? 为什么? The detailed information did not gave me any clues: 详细信息没有给我任何线索:

System.UnauthorizedAccessException was caught
  Message=Der Zugriff auf den Pfad "C:\Windows\System32\drivers\etc\hosts" wurde verweigert.
  Source=mscorlib
  StackTrace:
   bei System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath)
   bei 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)
   bei System.IO.FileStream..ctor(String path, FileMode mode, FileAccess access, FileShare share, Int32 bufferSize, FileOptions options, String msgPath, Boolean bFromProxy)
   bei System.IO.FileStream..ctor(String path, FileMode mode, FileAccess access, FileShare share, Int32 bufferSize, FileOptions options)
   bei System.IO.StreamWriter..ctor(String path, Boolean append, Encoding encoding, Int32 bufferSize)
   bei System.IO.StreamWriter..ctor(String path, Boolean append, Encoding encoding)
   bei System.IO.File.WriteAllLines(String path, String[] contents)
   bei App.HostsFile.Save() in HostsFile.cs:Zeile 125.
   bei App.Actions.SaveHosts.Execute(Context ctxt) in Actions\SaveHosts.cs:Zeile 16.
  InnerException: 
   (there is none)

I have not written a manifest file. 我尚未编写清单文件。 I am compiling with the default manifest option. 我正在使用默认清单选项进行编译。 So what is the problem? 那是什么问题呢? And what can I do? 那我该怎么办?

Thank you. 谢谢。

If you have UAC enabled you won't be able to write hosts, even if you're admin, unless you start the program in elevated mode to activate the admin privileges. 如果启用了UAC,即使您是管理员,也将无法编写主机,除非您以提升模式启动程序以激活管理员权限。

Please see here , and here for information on security permissions in code. 请参阅此处此处,以获取有关代码中的安全权限的信息。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

    namespace WriteToTheHosts
    {
        class Program
        {
            static void Main(string[] args)
            {
                var systemPath = Environment.GetFolderPath(Environment.SpecialFolder.System);
                Console.WriteLine(systemPath);
                var path = Path.Combine(systemPath, @"drivers\etc\hosts");
                using (var stream = new StreamWriter(path, true, Encoding.Default))
                {
                    stream.WriteLine("#from .NET");
                }
                Console.ReadKey();

            }
        }
    }

also turn off default manifest in project settings (Manifest: 'Create application without a manifest') and write your own manifest like showed in first link sample: 还关闭项目设置中的默认清单(清单:“创建没有清单的应用程序”),并编写自己的清单,如第一个链接示例所示:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<assembly xmlns="urn:schemas-microsoft-com:asm.v1" manifestVersion="1.0">
   <assemblyIdentity version="1.0.0.0" processorArchitecture="X86" name="WriteToTheHosts" type="win32"/>
      <trustInfo xmlns="urn:schemas-microsoft-com:asm.v3">
      <security>
         <requestedPrivileges>
            <requestedExecutionLevel level="requireAdministrator"/>
         </requestedPrivileges>
      </security>
   </trustInfo>
</assembly>

Never mind. 没关系。 I found the culprit. 我找到了罪魁祸首。 Everything is fine with UAC, but my Kaspersky was blocking my programs :-/ 使用UAC一切都很好,但是我的卡巴斯基阻止了我的程序:-/

Thank you, Alexander for your help. 谢谢亚历山大的帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 无法在C#中使用管理员权限写入主机文件 - Cannot write to hosts file with admin privileges in C# 无法从我的程序写入另一台计算机上的XML文件 - Cannot write to XML file in another computer from my program 无法从我的C#程序中运行.vbs脚本:“系统找不到指定的文件。” - Unable to run .vbs script from my C# program: “The system cannot find the file specified.” 运行程序时表格冻结 - Form freezes when I run my program 从WCF服务运行时,控制台程序的文本文件在哪里? - Where does my console program's text file go when it is run from a WCF service? 以管理员身份运行时出现“找不到文件”的程序错误 - Program errors with “File Not Found” when Run As Administrator 即使我的文件很小,maxreceivedmessagesize 也会出错 - Error with maxreceivedmessagesize even when my file is small C#:应用程序以管理员身份运行时未托管HTML文件 - C#: Html file not hosted when application run as admin 我在 C# 的 windows 服务无法写入文件,同时另一个 C# 应用程序正在尝试读取文件 - My windows service in C# cannot write to file, when at the same time another C# app is trying to read the file 即使具有管理员权限也无法删除注册表项 - Cannot Delete Registry Entry even with Admin Rights
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM