简体   繁体   English

从c#中的文本文件中读取整数并将它们写入数组

[英]Reading integers from text file in c# and writing them into array

I'm trying to read the values of pixels from text file and generate an image file. 我正在尝试从文本文件中读取像素值并生成图像文件。 But first I want to make sure that I can read all of the values in the file. 但首先我想确保我可以读取文件中的所有值。 I use this code, but the output misses some of the integers from the input file-the last ones. 我使用这段代码,但输出错过了输入文件中的一些整数 - 最后一个。 I don't know why! 我不知道为什么! Can you help me? 你能帮助我吗? Here's the code: 这是代码:

namespace txtToImg
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            TextWriter tw = new StreamWriter("D:\\out.txt");
            string fileContent = File.ReadAllText("D:\\in.txt");

            string[] integerStrings = fileContent.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);

            int[] integers = new int[integerStrings.Length];
            //tw.Write(integerStrings.Length);

            for (int n = 0; n < integerStrings.Length; n++)
            {
                integers[n] = int.Parse(integerStrings[n]);

                tw.Write(integers[n]+" ");


            }
        }
    }
}

I agree with Andrew's comment your streamWriter object isn't getting closed so for one thing I would try this. 我同意Andrew的评论你的streamWriter对象没有被关闭所以有一件事我会尝试这个。 I made the change below and attempted what you are doing and my output file contained all the entries. 我在下面进行了更改并尝试了您正在做的事情,我的输出文件包含所有条目。

 using (TextWriter tw = new StreamWriter(@"D:\out.txt"))
        {
            string fileContent = File.ReadAllText(@"D:\in.txt");

            string[] integerStrings = fileContent.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);

            int[] integers = new int[integerStrings.Length];

            for (int n = 0; n < integerStrings.Length; n++)
            {
                integers[n] = int.Parse(integerStrings[n]);
                tw.Write(integers[n] + " ");
            }
        }

是的,我刚刚运行它,因为我怀疑你的循环后需要以下内容:

tw.Close();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM