简体   繁体   English

只读取文本文件的第一行

[英]Read only first line from a text file

so what I'm failing to do is, MyFile.txt has either "english", "french" or "german" in the first line and I want to get the language from the first line of the text file, then continue my code所以我没有做的是,MyFile.txt 在第一行有“英语”、“法语”或“德语”,我想从文本文件的第一行获取语言,然后继续我的代码

String[] languages = new String[] { "english", "french", "german"};

foreach (String language in languages)
{
    string line1 = File.ReadLines("MyFile.txt").Skip(0).Take(1);
    line1 = language;
    continue;
}

You can make use of File.ReadLines together with Enumerable.First .您可以将File.ReadLinesEnumerable.First一起使用。 This guarantees you to only read the first line from the file.这保证您只能从文件中读取第一行。

using System.Linq; 

... ...

string line1 = File.ReadLines("MyFile.txt").First(); // gets the first line from file.

The difference to File.ReadAllLines is, that File.ReadLines makes use of lazy evaluation and doesn't read the whole file into an array of lines first.File.ReadAllLines的不同之处在于, File.ReadLines使用惰性求值,而不是先将整个文件读入行数组。

Linq also makes sure of properly disposing the FileStream. Linq 还确保正确处理 FileStream。

To comment on the use of ReadAllLines() in the OP's comment on the answer of CSharpie ;在 OP 对CSharpie答案的评论中评论ReadAllLines ReadAllLines()的使用; it may have a huge impact on the performance if MyFile.txt is a very large file.如果MyFile.txt是一个非常大的文件,它可能会对性能产生巨大影响。

File.ReadAllLines().First() will actually read all the lines, store them in a string[] and then take the first. File.ReadAllLines().First()实际上会读取所有行,将它们存储在string[] ,然后取第一行。 Therefore, if your file is very large, it will store all these lines in the array, which might take some time.因此,如果您的文件非常大,它会将所有这些行存储在数组中,这可能需要一些时间。

An alternative and better performing option would be to just open a StreamReader and read only the first line.另一种更好的选择是打开一个StreamReader并只读取第一行。 A correct implementation would be;正确的实现是;

String[] languages = new String[] { "english", "french", "german"};
string firstLine;

using(StreamReader reader = new StreamReader("MyFile.txt"))
{
    firstLine = reader.ReadLine() ?? "";
}

if(languages.Contains(firstLine))
{
    //...
}

The use of using will take care of closing and disposing the reader. using将负责关闭和配置阅读器。 Also, using ??另外,使用?? will make sure null is never returned (and thus saving you an ArgumentNullException on Contains() ).将确保永远不会返回null (从而为您节省一个ArgumentNullException on Contains() )。

Though the post is from 2014, a more efficient solution using a more recent method could be this one:虽然这篇文章是 2014 年的,但使用更新方法的更有效的解决方案可能是这个:

System.IO.StreamReader readingFile = new System.IO.StreamReader(filePath);

string readingLine = readingFile.ReadLine();

This way you prevent reading several lines and needing to get the first one with Linq.通过这种方式,您可以防止阅读多行并需要使用 Linq 获取第一行。

If the file is already opened by another process and concurrent reading is allowed, then something like this is needed.如果文件已被另一个进程打开并且允许并发读取,则需要这样的操作。 Otherwise a share violation exception is thrown.否则会引发共享冲突异常。

// Usage of "FileAccess.Read, FileShare.ReadWrite" prevents an avoidable
// exception when file is already opened with concurrent reading by 
// another process
using (var fileStream = new FileStream(@"MyFile.txt", FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
{
    using (var readerForFileStream = new StreamReader(fileStream))
    {
        string firstLine = readerForFileStream.ReadLine();

        if (firstLine != null)
        {
            // the file has a line
        }
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM