English 中文(简体)
使用StreamReader检查文件是否包含字符串
原标题:Using StreamReader to check if a file contains a string

我有一个<code>args[0]</code>的字符串。

这是我迄今为止的代码:

static void Main(string[] args)
{
    string latestversion = args[0];
    // create reader & open file
    using (StreamReader sr = new StreamReader("C:\Work\list.txt"))
    {
        while (sr.Peek() >= 0)
        {
            // code here
        }
   }
}

我想检查我的list.txt文件是否包含args[0]。如果是,则我将创建另一个进程StreamWriter,将字符串10写入文件。我该怎么做?

最佳回答

你预计这个文件会特别大吗?如果没有,最简单的方法就是通读:

using (StreamReader sr = new StreamReader("C:\Work\list.txt"))
{
    string contents = sr.ReadToEnd();
    if (contents.Contains(args[0]))
    {
        // ...
    }
}

或者:

string contents = File.ReadAllText("C:\Work\list.txt");
if (contents.Contains(args[0]))
{
    // ...
}

或者,您可以逐行阅读:

foreach (string line in File.ReadLines("C:\Work\list.txt"))
{
    if (line.Contains(args[0]))
    {
        // ...
        // Break if you don t need to do anything else
    }
}

或者更像LINQ:

if (File.ReadLines("C:\Work\list.txt").Any(line => line.Contains(args[0])))
{
    ... 
}

请注意,ReadLines只能从.NET4中获得,但您可以很容易地在循环中调用TextReader.ReadLine

问题回答
  1. You should not add the ; at the end of the using statement.
  2. 工作代码:

    string latestversion = args[0];
    
    using (StreamReader sr = new StreamReader("C:\Work\list.txt"))
    using (StreamWriter sw = new StreamWriter("C:\Work\otherFile.txt"))
    {
            // loop by lines - for big files
            string line = sr.ReadLine();
            bool flag = false;
            while (line != null)
            {
                if (line.IndexOf(latestversion) > -1)
                {
                    flag = true;
                    break;
                }
                line = sr.ReadLine();
            }
            if (flag)
                sw.Write("1");
            else
                sw.Write("0");
    
            // other solution - for small files
            var fileContents = sr.ReadToEnd();
            {
                if (fileContents.IndexOf(latestversion) > -1)
                    sw.Write("1");
                else
                    sw.Write("0");
            }
    }   
    
if ( System.IO.File.ReadAllText("C:\Work\list.txt").Contains( args[0] ) )
{
...
}

接受的答案读取内存中可能正在消耗的所有文件。

这是一个受VMAtm答案启发的替代方案

using (var sr = new StreamReader("c:\path\to\file", true))
    for (string line; (line = sr.ReadLine()) != null;) //read line by line
        if (line.Contains("mystring"))
            return true;




相关问题
Anyone feel like passing it forward?

I m the only developer in my company, and am getting along well as an autodidact, but I know I m missing out on the education one gets from working with and having code reviewed by more senior devs. ...

NSArray s, Primitive types and Boxing Oh My!

I m pretty new to the Objective-C world and I have a long history with .net/C# so naturally I m inclined to use my C# wits. Now here s the question: I feel really inclined to create some type of ...

C# Marshal / Pinvoke CBitmap?

I cannot figure out how to marshal a C++ CBitmap to a C# Bitmap or Image class. My import looks like this: [DllImport(@"test.dll", CharSet = CharSet.Unicode)] public static extern IntPtr ...

How to Use Ghostscript DLL to convert PDF to PDF/A

How to user GhostScript DLL to convert PDF to PDF/A. I know I kind of have to call the exported function of gsdll32.dll whose name is gsapi_init_with_args, but how do i pass the right arguments? BTW, ...

Linqy no matchy

Maybe it s something I m doing wrong. I m just learning Linq because I m bored. And so far so good. I made a little program and it basically just outputs all matches (foreach) into a label control. ...

热门标签