【问题标题】:C# find a specific line from a text file / display to listviewC# 从文本文件中查找特定行/显示到列表视图
【发布时间】:2019-02-16 18:26:20
【问题描述】:

以下是步骤: 1. 浏览到一个文本文件 2.将文本加载到文本框中 3.从文本中找到特定的行/位置 4. 显示在一个 3 列的 LISTVIEW 中。

我现在的做法是这样的:

listview1.Items.Add(new ListViewItem(new[] { "1", "Type", text1.Substring(0, 12) }));

listview1.Items.Add(new ListViewItem(new[] { "2", "ID", text1.Substring(13, 2) }));

listview1.Items.Add(new ListViewItem(new[] { "3", "Name", text1.Substring(15, 3) }));

listview1.Items.Add(new ListViewItem(new[] { "4", "DOB", text1.Substring(17, 2) }));

listview1.Items.Add(new ListViewItem(new[] { "5", "Version", text1.Substring(18, 7) }));

它正在工作......直到我遇到一个长度小于我的子字符串代码的文本文件。我遇到了崩溃(OutOfRangeException)

我想知道是否有更好的编码方式。如果没有,解决 OutOfRangeExceptiion 错误的最佳方法是什么。

作为一种解决方法,我正在使用 text1.padright(999) 来增加我加载的任何文本文件的长度。但可能有更好的解决方案。

谢谢!

【问题讨论】:

    标签: c# listview substring


    【解决方案1】:

    我可以建议添加这样的扩展方法:

    public static class Ext 
    {
        public static string SubstringWithCheck(this string text, int start, int length, string replace = "")
        {
            if (text.Length < start + length)
            {
                return replace;
            }
            return text.Substring(start, length);
        }
    }
    

    那么你可以使用这个方法:

    listview1.Items.Add(new ListViewItem(new[] { "1", "Type", text1.SubstringWithCheck(0, 12) }));
    

    或者像这样:

    listview1.Items.Add(new ListViewItem(new[] { "1", "Type", text1.SubstringWithCheck(0, 12, "your text here") }));
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-07-10
      • 2020-05-01
      • 1970-01-01
      • 2013-09-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多