2012-12-24 31 views
1

我正在尝试读取我的apache日志并使用它进行一些处理。我使用了一个字符串分割函数,它包含以这种方式引用我的日志行。我想删除这些行。下面的代码显示我有。它只会删除“127.0.0.1”,但会出现所有“192.168.1.x”行。在C#中分割返回的每个项目的文本行搜索行

如何删除EVERY拆分字符串?

 public void GetTheLog() 
    { 
     string path = "c:\\program files\\Zend\\apache2\\logs\\access.log"; 
     string path2 = @"access.log"; 
     int pos; 
     bool goodline = true; 

     string skipIPs = "127.0.0.1;192.168.1.100;192.168.1.101;192.168.1.106;67.240.13.70"; 
     char[] splitchar = { ';' }; 
     string[] wordarray = skipIPs.Split(splitchar); 
     FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite); 
     StreamReader reader = new StreamReader(fs); 
     TextWriter tw = new StreamWriter(path2); 

     while (!reader.EndOfStream) 
     { 
      string line = reader.ReadLine(); 

      // initialize goodline for each line of reader result 
      goodline = true; 
      for (j = 0; j < wordarray.Length; j++) 
      { 
       pos = -10; 
       srch = wordarray[j]; 
       ln = line.Substring(0,srch.Length); 
       pos = ln.IndexOf(srch); 
       if (pos >= 0) goodline = false; 
      } 
      if (goodline == true) 
      { 
       tw.WriteLine(line); 
       listBox2.Items.Add(line); 
      } 
     } 

     // Clean up 
     reader.Close(); 
     fs.Close(); 
     listBox1.Items.Add(path2); 
     tw.Close(); 
    } 

回答

1
var logPath = @"c:\program files\Zend\apache2\logs\access.log"; 
var skipIPs = "127.0.0.1;192.168.1.100;192.168.1.101;192.168.1.106;67.240.13.70"; 
var filters = skipIPs.Split(';'); 
var goodlines = File.ReadLines(logPath) 
        .Where(line => !filters.Any(f => line.Contains(f))); 

然后你可以

File.WriteAllLines(@"access.log", goodlines); 

而且它也像你行卸入一个列表框

listBox2.Items.AddRange(goodlines.Select(line=> new ListItem(line)).ToArray()); 

而且,由于你的skipIPs只是一个静态的字符串,你可以重构一点,只是做

var filters = new []{"127.0.0.1","192.168.1.100","192.168.1.101",...}; 
+0

谢谢。我不得不稍微修改你的回复。我得到了“文件无法访问......正在被另一个程序使用”的错误信息,所以我将它下载到一个临时文件中,就像我最初做的那样,然后添加了将它们应用到临时文件的建议。这就是诀窍! –

+0

@DaveJaswaye超级,很高兴听到它。如果你是新手,请考虑将此标记为正确答案或对其进行投票。 – Bert

0

arrrrrr喧嚣得到你想要的......

OKH让您是否要删除所有存在于你的skipIPs从当前文件中的IP地址我试试。

,那么你可以简单地使用....

if(ln==srch) 
    { 
    goodline = false; 
    } 

,而不是

pos = ln.IndexOf(srch); 
    if (pos >= 0) goodline = false; 

里面的for循环。

希望它会jelp你... :)

+0

谢谢! (Duhhh!)我认为我过于复杂了。总是厌倦重新加载程序。 –