2

我正在编写一个程序,该程序将从 AS400 获取数据,并且需要读取文本的第一行以确定文件的位置。AS400 的数据中有很多不可打印的字符。

这是我的工作代码:

//LINQ to read first line and find what I need
var lines = File.ReadAllLines(as400file);
foreach (string line in lines)
{
    //Regex the AS400 garbage out of there...
    string replaced = Regex.Replace(line, @"[^\u0000-\u007F]", String.Empty);
    /*  ^ = not
    *  \u0000 - \u007F is the first 127 chars of UTF-8
    *  So this replaces all non ascii chars with an empty string
    */

    //Rest of program code
}

但是我真的只想要文件的第一行而不是每一行。我似乎想不出一种只获得第一行的方法,而且我对 linq 的经验并不丰富。任何指示或帮助?

4

4 回答 4

1
var line = File.ReadAllLines(as400file).First(line => !string.IsNullOrWhitespace(line));
string replaced = Regex.Replace(line, @"[^\u0000-\u007F]", String.Empty);

难道……这就是你想要的吗?

于 2013-11-05T17:32:04.833 回答
1

尝试以下操作,它将从文件中读取一行。

string line;

using (var file = new StreamReader(as400file))
{
    line = file.ReadLine();
}

string replaced = Regex.Replace(line, @"[^\u0000-\u007F]", String.Empty);
于 2013-11-05T17:34:39.150 回答
0

作为亚历克斯回答的替代方案,您可以使用 StreamReader 来获取第一行:

using (var reader = new System.IO.StreamReader(as400File))
{
    var line = reader.ReadLine();
    string replaced = Regex.Replace(line, @"[^\u0000-\u007F]", String.Empty);
}
于 2013-11-05T17:35:00.083 回答
0

感谢 Alex 的帮助,这是我的工作代码:

//LINQ to read first line and find what I need
var lines = File.ReadAllLines(testfile).First(line => !string.IsNullOrWhiteSpace(line));
//Regex the AS400 garbage out of there...
string replaced = Regex.Replace(lines, @"[^\u0000-\u007F]", String.Empty);
/*  ^ = not
 *  \u0000 - \u007F is the first 127 chars of UTF-8
 *  So this replaces all non ascii chars with an empty string
 */
于 2013-11-06T13:00:20.547 回答