2016-05-16 29 views
-1

我是新来的编码,我陷入了下面的问题。我得到一个存储在文本文件中的数据集,并在buttonclick(Forms)上将每列数据写入三个文本框。这工作得很好:以原始文本格式存储数据

1. IMG "left my dataset, right: the output in forms"

但我有问题,当我在文本框中编辑数据,并将其存储在buttonclick成文本文件,同时保持完全相同的格式原来TXT文件。

这是我所得到的目前我的代码:

2.IMG "Wrong format"

我的问题是,我该如何让我的数组的前三个元素融入其中线和接下来的三个元素融入到第二行等等,以获得原始格式?我尝试了各种拆分方法,但无法运行。

这里是我的代码:

private void button1_Click(object sender, EventArgs e) 
{ 
    this.textBox1.Text = null; 
    this.textBox2.Text = null; 
    this.textBox3.Text = null; 

    string[] input = System.IO.File.ReadAllLines(@"C:\Users\Dan\Desktop\NEW.txt"); 

    // sets new string 
    string words = ""; 

    for (int k = 0; k < input.Length; k++) 
    { 
     words = words + input[k] + " "; 
    } 

    // converts string type "words" to string array "lines" 
    string[] lines = words.Split(' '); 

    for (int i = 0; i < lines.Length - 1; i = i + 3) 
    { 
     textBox1.Text += lines[i] + "\r\n"; 
     textBox2.Text += lines[i + 1] + "\r\n"; 
     textBox3.Text += lines[i + 2] + "\r\n"; 
    } 
} 

private void button2_Click(object sender, EventArgs e) 
{ 
    string[] output = (this.textBox1.Text + this.textBox2.Text + this.textBox3.Text).Split('\r'); 

    string hello = ""; 

    for (int i = 0; i < 3; i++) 
    { 
     hello += output[i] + output[i + 3] + output[i + 6]; 
    } 

    File.WriteAllText(@"C:\Users\Dan\Desktop\Output.txt",hello); 
} 
+0

你现在这样做的方式有什么问题?你能添加另一张图片来澄清吗? – PhilDulac

+0

嗨,我认为第二个图像是足够清晰的,因为格式不同于第一个。我只想从第一张图片(左) – Dan

+0

以“原始”格式写入文本文件[您是否尝试过调试](http://ericlippert.com/2014/03/05/how-to-debug-小程序/)?我遇到的第一个问题是你用'“\ r \ n”'加入文件行,但是当你编写时只分割''\ r''。那么''\ n''s怎么样? –

回答

1

首先,你需要做这样的分裂,妥善处理回车:

string[] output = (this.textBox1.Text + this.textBox2.Text + this.textBox3.Text).Split(new [] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries); 

然后你就可以重建原始文件格式:

hello += string.Format("{0} {1} {2}{3}", output[i], output[i + 3], output[i + 6], Environment.NewLine); 
相关问题