通过在 C# 中拆分每一行来读取文件

Read File by Splitting Each Row in C#

我试图通过在 c# 中通过 regex.split 删除空格来拆分每一行来读取文件,但我的代码无法正常工作需要帮助。提前致谢。

        text="";
        OpenFileDialog open = new OpenFileDialog();
        if (open.ShowDialog() == System.Windows.Forms.DialogResult.OK)
        {
            Stream filestream = open.OpenFile();
            if (filestream != null)
            {
                string filename = open.FileName;
                text = File.ReadAllText(filename);
            }


            string code = textBox1.Text;
            columncounter = code.Length;
            string[] arrays = Regex.Split(code, @"\s+");
            textBox1.Text = text;

        }

只需添加 textBox1.text = string.Concat(arrays)。它将连接拆分数组中的字符串。

或者你可以做类似 text.Replace(" ", "")

如果您尝试将每一行不带空格地写入您的文本框,这应该可行:

var result = new StringBuilder();
foreach (var line in File.ReadAllLines(filename))
{
    result.AppendLine(Regex.Replace(line, @"\s", "")));
}

textBox1.Text = result.ToString();

为了更快的性能,使用string.Replace:

var result = new StringBuilder();

foreach (var line in File.ReadAllLines(filename))
{
    result.AppendLine(line
        .Replace("\t", "")
        .Replace("\n", "")
        .Replace("\r", "")
        .Replace(" ", ""));
}

textBox1.Text = result.ToString();