c# - 文本文件只读取奇数或偶数行?

标签 c# file-io

我正在尝试编写一个小的 C# 程序,该程序从文本文件中读取数据并让您选择要打印的行。

出于某种原因,它只会打印第 1、3、5 行等

如果我将 int chooseLine = Convert.ToInt32(input); 更改为 int chooseLine = (int)Convert.ToInt64(input);,那么它只打印偶数行。(0、2、4、6 等)。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
class Steve
{
    public static int count = 0;
    public static String[] steveTalk;
    public static void Main()
    {
        using (StreamReader r = new StreamReader("Steve.txt"))
        {
            string line;
            while ((line = r.ReadLine()) != null)
            {
                count++;
            }
        }
        using (StreamReader sr = new StreamReader("Steve.txt"))
        {
            int i = 0;
            steveTalk = new String[count];
            String line;
            while ((line = sr.ReadLine()) != null)
            {
                steveTalk[i] = line;
                Console.WriteLine(steveTalk[i]);
                i++;
            }
        }
        while (true)
        {
            string input = Console.ReadLine();
            int chooseLine = Convert.ToInt32(input);
            try
            {
                Console.WriteLine(steveTalk[chooseLine]);
            }
            catch
            {
                Console.WriteLine("Error! Not a number or array index out of bounds");
            }
            Console.ReadLine();
        }
    }
}

有什么想法吗?

最佳答案

我想推荐 System.IO.File.ReadAllLines(filename) 方法。

string []lines=System.IO.File.ReadAllLines("Steve.txt");

string input ;

while ((input = Console.ReadLine()) != "end")
    {
        int chooseLine;
        int.TryParse(input,out chooseLine);
        if(chooseLine<lines.Length)
         {
           Console.WriteLine(lines[chooseLine]);
         }
    }

关于c# - 文本文件只读取奇数或偶数行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8380585/

相关文章:

c# - Flash ActiveX API 文档?

c# - Viewinjection 统一失败

c - 文件 IO 段错误

c# - Automapper 全局目标实例化器

c# - MVC3 和 session 可扩展性

php - 从 PHP GD 中的文件输出动画 GIF

file-io - JSR 352 : How do you write to a MVS Dataset from a Java Batch program?

c - 将多个结构保存到二进制文件中 (C)

c# - Windows UI 自动化 : click tray icon button

vb.net - 从 .NET 应用程序使用 if 条件运行 Powershell 脚本