C# Linq and Regexing non-unicode



>我正在编写一个程序,该程序将从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 没有那么丰富的经验。有什么指示或帮助吗?

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

这就是你想要的吗?

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

string line;
using (var file = new StreamReader(as400file))
{
    line = file.ReadLine();
}
string replaced = Regex.Replace(line, @"[^u0000-u007F]", String.Empty);

作为 Alex 答案的替代方法,您可以使用 StreamReader 来获取第一行:

using (var reader = new System.IO.StreamReader(as400File))
{
    var line = reader.ReadLine();
    string replaced = Regex.Replace(line, @"[^u0000-u007F]", String.Empty);
}

感谢 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
 */

最新更新