簡體   English   中英

讀取.txt文件並顯示該文件中的數字

[英]reading a .txt file and displaying numbers from the file

我正在嘗試使用c#讀取.txt文件並顯示其內容,但出現IndexOutOfRangeException錯誤,錯誤代碼為0xc000013a

這是我的代碼:

static void Main(string[] args)
    {
        StreamReader sStreamReader = new StreamReader("d:\\TEST.txt");
        while (!sStreamReader.EndOfStream)
        {
            string sLine = "";
            if (sLine != null)
            {
                sLine = sStreamReader.ReadLine();
                if (sLine != null)
                {
                    string[] rows = sLine.Split(",".ToCharArray());
                    double a = Convert.ToDouble(rows[1]);
                    Console.Write(a);
                    int b = Convert.ToInt32(rows[3]);
                    Console.WriteLine(b);
                    Console.WriteLine();
                }
            }
        }
    }

我的文本文件如下:

1,2,3,4,5,6,7

1,2,3,4,5,6,7

5,6,2,7,3,8,4

3,4,3,4,3

5,3,23,12

12,30000,12,99

我將其更改為以下內容:

static void Main(string[] args)
    {
        // StreamReader is IDisposable which should be wrapped in a using statement
        using (StreamReader reader = new StreamReader(@"d:\TEST.txt")) 
        {
            while (!reader.EndOfStream)
            {
                string line = reader.ReadLine();
                // make sure we have something to work with
                if (String.IsNullOrEmpty(line)) continue;

                string[] cols = line.Split(',');
                // make sure we have the minimum number of columns to process
                if (cols.Length < 4) continue;

                double a = Convert.ToDouble(cols[1]);
                Console.Write(a);
                int b = Convert.ToInt32(cols[3]);
                Console.WriteLine(b);
                Console.WriteLine();
            }
        }
    }

這里有一些注意事項:

  1. StreamReader實現IDisposable,因此應將其包裝在using子句中,以便對其進行正確處理。
  2. 不要命名“ sLine”之類的東西。 這種形式的匈牙利人通常被認為是嚴重的不良做法。 甚至微軟也表示不這樣做。
  3. 您正在處理的是列,而不是行。 因此,該變量應適當命名。
  4. 在盲目訪問它們之前,請務必進行測試以確保擁有所需的所有列。
  5. 通常,我不會使用Convert.ToDouble或Convert.ToInt32。 使用TryParse來確保它能夠轉換要安全得多。 如果cols [1]和cols [3]具有非數字數據,您擁有的代碼將被吹滅。
  6. 您可以在字符串前面使用@符號,以告訴編譯器不需要對其進行轉義。
  7. 只需簡單地“繼續”循環而不是將其包裝在if語句中,就更清潔了。
  8. 將String變量設置為空白字符串,然后立即將其設置為其他值,將導致空白在整個作用域中保留在內存中。 換句話說,這浪費了內存。 當然,在這種情況下,這是微優化,但始終使用最佳實踐絕不會造成傷害。

您是否考慮row.Length在訪問row[1]row[3]之前檢查row.Length

我懷疑您的空白行是問題

這是使您更簡單的方法:

        string[] lines = File.ReadAllLines("d:\\TEST.txt");
        foreach (var line in lines.Where(line => line.Length > 0))
        {
            string[] numbers = line.Split(',');

            // It checks whether numbers.Length is greater than 
            // 3 because if maximum index used is 3 (numbers[3]) 
            // than the array has to contain at least 4 elements
            if (numbers.Length > 3)
            {
                double a = Convert.ToDouble(numbers[1]);
                Console.Write(a);
                int b = Convert.ToInt32(numbers[3]);
                Console.Write(b);
                Console.WriteLine();
            }
        }

您應該考慮使用:

if (!string.IsNullOrEmpty(sLine))

代替

if (sLine != null)

因為有些行為空,所以您有此例外。

但是,這是使用StreamReader時應編寫代碼的一種方式:

using(var reader = new StreamReader(@"d:\\TEST.txt"))
{
    string line;
    while ((line= reader.ReadLine()) != null)
    {
        if (string.IsNullOrEmpty(line)) continue;

        var rows = line.Split(",".ToCharArray());
        var a = Convert.ToDouble(rows[1]);
        Console.Write(a);
        var b = Convert.ToInt32(rows[3]);
        Console.WriteLine(b);
        Console.WriteLine();
    }
}

問候,

凱文

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM