我有一个txt文件包含:
#
#test
this is a test
127.0.0.1 test69.com
127.0.0.1 http://test69.com
127.0.0.1 www.test69.com
127.0.0.1 man.test
127.0.0.1 http://man.test
127.0.0.1 www.man.test
127.0.0.1 www.another.test
如何将所有行加载到列表框中,但只在列表框中保留3行,如:
test69.com
man.test
another.test
示例:我的代码运行良好,但我无法避免我的列表框已加载www.test69.com
和http://test69.com
但我不想要它们,我只想要test69.com
出现< / p>
string str = "";
StreamReader sr = new StreamReader("C:\\Users\\GhoSter\\Desktop\\test.txt");
while ((str = sr.ReadLine()) != null)
{
if (Check(str) == true)
{
string localip = str.Substring(0,9);
string load = str.Replace(localip + " ", "");
myList.Add(load);
}
}
this.listBox1.DataSource = myList;
}
bool Check(string s)
{
bool flag = false;
if (s == "" || s == null)
flag = false;
else
{
string first = s.Substring(0, 1);
switch (first)
{
case "0":
case "1":
case "2":
case "3":
case "4":
case "5":
case "6":
case "7":
case "8":
case "9":
flag = true;
break;
default:
flag = false;
break;
}
}
return flag;
}
答案 0 :(得分:2)
您可以使用Uri
类来解析和验证它并删除协议。然后使用Enumerable.Distinct
删除重复项:
var listOfDistinctUrls = File.ReadLines(@"PathToTextFile");
.Where(l => !string.IsNullOrWhiteSpace(l))
.Select(l => {
string token = l.Split().Last();
Uri uri;
if (Uri.TryCreate(token, UriKind.RelativeOrAbsolute, out uri))
{
string fileName = Path.GetFileName(uri.IsAbsoluteUri ? uri.Host + uri.PathAndQuery : uri.ToString());
int wwwIndex = fileName.IndexOf("www.", 0, StringComparison.OrdinalIgnoreCase);
return wwwIndex >= 0 ? fileName.Substring(wwwIndex + 4) : fileName;
}
else
return null;
})
.Where(u => !string.IsNullOrWhiteSpace(u))
.Distinct()
.ToList();
结果:
test69.com
man.test
答案 1 :(得分:1)
在这里如何做到这一点
string[] lines =File.ReadAllLines(yourpathFile);
//in your listbox
listBox1.Items.AddRange(lines.Take(6).ToArray());
答案 2 :(得分:1)
我想你想要没有“www”&amp;的不同名字来自文本文件中所有行的ip地址
注意: - 如果有错,请对请求的评论仍然明确。这只是为了过滤字符串。按照你的逻辑对列表框做的。
试试此代码
string[] lines = File.ReadAllLines(AppDomain.CurrentDomain.BaseDirectory + @"\fil.txt");
int ctr = 0;
foreach (var item in lines)
{
string tmp = item;
tmp = tmp.Replace("127.0.0.1", "");
tmp = tmp.Replace("http://", "");
tmp = tmp.Replace("www.", "");
tmp = tmp.Trim();
if (ctr < lines.Length)
{
lines[ctr] = tmp;
ctr++;
}
}
//to skip initial lines
var result = lines.Skip(3).Distinct();
答案 3 :(得分:1)
试试这个:
List<string> arr = new List<string>();
StreamReader r = File.OpenText( Server.MapPath("b.txt"));
while (!r.EndOfStream)
{
Match match = Regex.Match(r.ReadLine(), @"(www.|http://)([\w.]+)$");
if (match.Success)
{
arr.Add(Regex.Replace(match.Value, @"(http://|www.)", ""));
}
}
ListBox1.DataSource = arr.Distinct();
ListBox1.DataBind();
输出: