1

我正在尝试阅读我的 apache 日志并对其进行一些处理。我使用一个字符串拆分函数,其中包含以这种方式引用我的日志行。我想删除这些行。下面的代码表明我有。它只删除“127.0.0.1”,但出现所有“192.168.1.x”行。

如何删除每个拆分字符串?

        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();
    }
4

2 回答 2

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",...};
于 2012-12-24T02:51:20.877 回答
0

arrrrrr din得到你想要的......

好的,如果您想从当前文件中删除跳过 IP 中存在的所有 IP,让我试试。

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

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

代替

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

在你的 for 循环中。

希望它会刺激你... :)

于 2012-12-24T06:30:26.990 回答