c # program by modifying the hosts file

Alternatively ip 1

var OSInfo = Environment.OSVersion;
string pathpart = "hosts";
if (OSInfo.Platform == PlatformID.Win32NT)
{
    //is windows NT
    pathpart = "system32\\drivers\\etc\\hosts";
}
string hostfile = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Windows), pathpart);

const string tales = "123.123.123.123 download.talesrunner.com";
if (!File.ReadAllLines(hostfile).Contains(tales))
{
    File.AppendAllLines(hostfile, new String[] { tales });
}

2 domain name replacement

 const string tales = "123.123.123.123 download.talesrunner.com";
    string[] lines = File.ReadAllLines(hostfile);

    if (lines.Any(s => s.Contains("download.talesrunner.com")))
    {
        for (int i = 0; i < lines.Length; i++)
        {
             if (lines[i].Contains("download.talesrunner.com"))
                 lines[i] = tales;
        }
        File.WriteAllLines(hostfile, lines);
    }
    else if (!lines.Contains(tales))
    {
        File.AppendAllLines(hostfile, new String[] { tales });
    }

3 Additional direct

public static bool ModifyHostsFile(string entry)    
{    
    try    
    {    
        using (StreamWriter w = File.AppendText(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.System), @"drivers\etc\hosts")))    
        {    
            w.WriteLine(entry);    
            return true;    
        }    
    }    
    catch (Exception ex)    
    {    
        Console.WriteLine(ex.Message);    
        return false;    
    }    
}  

 

Guess you like

Origin www.cnblogs.com/wolbo/p/12310850.html