[英]Reading integers from text file in c# and writing them into array
我正在嘗試從文本文件中讀取像素值並生成圖像文件。 但首先我想確保我可以讀取文件中的所有值。 我使用這段代碼,但輸出錯過了輸入文件中的一些整數 - 最后一個。 我不知道為什么! 你能幫助我嗎? 這是代碼:
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]+" ");
}
}
}
}
我同意Andrew的評論你的streamWriter對象沒有被關閉所以有一件事我會嘗試這個。 我在下面進行了更改並嘗試了您正在做的事情,我的輸出文件包含所有條目。
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.