这是一个奇怪的问题,但我似乎无法解决它。
我正在创建一个可视化用户界面来修改 Debian Wheezy(以及偶然兼容的其他 debian 版本/衍生物)上的互联网设置。
我希望能够根据用户插入的内容修改 DNS。
按下“保存”后,运行以下代码:
void SaveDNSButton_event(object obj, ButtonPressEventArgs args)
{
//save dns settings
string s1 = "";
string s2 = "";
string toWrite = s1 + s2;
Console.WriteLine ("=============");
Console.WriteLine ("Reading from resolv.conf before writing...");
using (StreamReader confReader = File.OpenText ("/etc/resolv.conf")) {
StringReader sr = new StringReader (confReader.ReadToEnd ());
string line;
toWrite = "";
while (null != (line = sr.ReadLine ())) {
if (line.Contains ("nameserver")) {
Console.WriteLine (line);
} else {
toWrite += line + Environment.NewLine;
}
}
confReader.Dispose ();
confReader.Close ();
}
s1 = "nameserver " + DNSentry1.Text + ";" + Environment.NewLine;
s2 = "nameserver " + DNSentry2.Text + ";" + Environment.NewLine;
Console.WriteLine ("=============");
Console.WriteLine ("Writing to resolv.conf");
Console.WriteLine ("To write: " + toWrite + s1 + s2);
using (StreamWriter confWriter = new StreamWriter ("/etc/resolv.conf", false)) {
Console.WriteLine ("Writing...");
confWriter.Write (toWrite + s1 + s2);
Console.WriteLine ("Closing file stream...");
confWriter.Dispose ();
confWriter.Close ();
}
Console.WriteLine ("=============");
Console.WriteLine ("Opening conf to confirm if it worked");
if (IsLinux) {
Console.WriteLine ("Trying to open conf");
StreamReader file = File.OpenText ("/etc/resolv.conf");
string s = file.ReadToEnd ();
Console.WriteLine(s);
file.Dispose ();
file.Close ();
}
}
相关部分是
using (StreamWriter confWriter = new StreamWriter ("/etc/resolv.conf", false)) {
Console.WriteLine ("Writing...");
confWriter.Write (toWrite + s1 + s2);
Console.WriteLine ("Closing file stream...");
confWriter.Dispose ();
confWriter.Close ();
}
其中我resolv.conf
用填写的 DNS 信息覆盖。输入的示例类似于第一个对话框中的“8.8.8.8”和第二个对话框中的“8.8.4.4”。输出将是...
=============
Reading from resolv.conf before writing...
nameserver 192.168.2.101
nameserver 8.8.8.8
=============
Writing to resolv.conf
To write: # Generated by NetworkManager
domain trin-it.local
search trin-it.local
nameserver 8.8.8.8;
nameserver 8.8.4.4;
Writing...
Closing file stream...
=============
Opening conf to confirm if it worked
4
Trying to open conf
# Generated by NetworkManager
domain trin-it.local
search trin-it.local
nameserver 8.8.8.8;
nameserver 8.8.4.4;
如果我在此之后 ping google,它只会说:“未知主机 google”
但是,如果我手动转到resolv.conf
并更改那里的名称服务器,它实际上可以很好地解析。这是怎么回事?/etc/resolv.conf
据我所知,唯一的变化是我通过代码而不是仅仅 nano 来完成此操作。有人能解释一下吗?
长话短说
为什么使用代码编辑 resolv.conf 与手动编辑它相比不起作用?难道不是同一件事吗?
答案1
在我看来,您的代码在名称服务器行的末尾添加了一个分号;不要那样做。